├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── bccsp ├── aesopts.go ├── bccsp.go ├── bccsp_test.go ├── ecdsaopts.go ├── factory │ ├── factory.go │ ├── factory_test.go │ ├── nopkcs11.go │ ├── opts.go │ ├── opts_test.go │ ├── pkcs11.go │ ├── pkcs11_test.go │ ├── pkcs11factory.go │ ├── pkcs11factory_test.go │ ├── swfactory.go │ └── swfactory_test.go ├── hashopts.go ├── keystore.go ├── mocks │ └── mocks.go ├── opts.go ├── pkcs11 │ ├── conf.go │ ├── ecdsa.go │ ├── ecdsa_test.go │ ├── ecdsakey.go │ ├── ecdsakey_test.go │ ├── impl.go │ ├── impl_test.go │ ├── pkcs11.go │ └── pkcs11_test.go ├── rsaopts.go ├── signer │ ├── signer.go │ └── signer_test.go ├── sw │ ├── aes.go │ ├── aes_test.go │ ├── aeskey.go │ ├── conf.go │ ├── dummyks.go │ ├── dummyks_test.go │ ├── ecdsa.go │ ├── ecdsa_test.go │ ├── ecdsakey.go │ ├── enc_test.go │ ├── fileks.go │ ├── fileks_test.go │ ├── hash.go │ ├── hash_test.go │ ├── impl.go │ ├── impl_test.go │ ├── internals.go │ ├── keyderiv.go │ ├── keyderiv_test.go │ ├── keygen.go │ ├── keygen_test.go │ ├── keyimport.go │ ├── keyimport_test.go │ ├── mocks │ │ └── mocks.go │ ├── rsa.go │ ├── rsa_test.go │ ├── rsakey.go │ ├── sign_test.go │ ├── sw_test.go │ └── verify_test.go └── utils │ ├── errs.go │ ├── errs_test.go │ ├── io.go │ ├── io_test.go │ ├── keys.go │ ├── keys_test.go │ ├── slice.go │ ├── slice_test.go │ ├── x509.go │ └── x509_test.go ├── common ├── cauthdsl │ ├── cauthdsl.go │ ├── cauthdsl_builder.go │ ├── cauthdsl_test.go │ ├── policy.go │ ├── policy_test.go │ ├── policy_util.go │ ├── policyparser.go │ └── policyparser_test.go ├── config │ ├── api.go │ ├── application.go │ ├── application_test.go │ ├── application_util.go │ ├── applicationorg.go │ ├── applicationorg_test.go │ ├── channel.go │ ├── channel_test.go │ ├── channel_util.go │ ├── consortium.go │ ├── consortium_test.go │ ├── consortiums.go │ ├── consortiums_test.go │ ├── consortiums_util.go │ ├── msp │ │ ├── config.go │ │ ├── config_test.go │ │ └── config_util.go │ ├── orderer.go │ ├── orderer_test.go │ ├── orderer_util.go │ ├── organization.go │ ├── organization_test.go │ ├── proposer.go │ ├── proposer_test.go │ ├── realconfig_test.go │ ├── root.go │ ├── root_test.go │ ├── standardvalues.go │ └── standardvalues_test.go ├── configtx │ ├── api │ │ └── api.go │ ├── compare.go │ ├── compare_test.go │ ├── config.go │ ├── config_test.go │ ├── configmap.go │ ├── configmap_test.go │ ├── initializer.go │ ├── manager.go │ ├── manager_test.go │ ├── template.go │ ├── template_test.go │ ├── test │ │ ├── helper.go │ │ └── helper_test.go │ ├── tool │ │ ├── configtxgen │ │ │ ├── main.go │ │ │ ├── main_test.go │ │ │ └── metadata │ │ │ │ ├── metadata.go │ │ │ │ └── metadata_test.go │ │ ├── localconfig │ │ │ └── config.go │ │ └── provisional │ │ │ ├── provisional.go │ │ │ └── provisional_test.go │ ├── update.go │ ├── update_test.go │ ├── util.go │ └── util_test.go ├── crypto │ ├── random.go │ ├── secp256k1 │ │ ├── .gitignore │ │ ├── curve.go │ │ ├── ext.h │ │ ├── libsecp256k1 │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── COPYING │ │ │ ├── Makefile.am │ │ │ ├── README.md │ │ │ ├── TODO │ │ │ ├── autogen.sh │ │ │ ├── build-aux │ │ │ │ └── m4 │ │ │ │ │ ├── ax_jni_include_dir.m4 │ │ │ │ │ ├── ax_prog_cc_for_build.m4 │ │ │ │ │ └── bitcoin_secp.m4 │ │ │ ├── configure.ac │ │ │ ├── contrib │ │ │ │ ├── lax_der_parsing.c │ │ │ │ ├── lax_der_parsing.h │ │ │ │ ├── lax_der_privatekey_parsing.c │ │ │ │ └── lax_der_privatekey_parsing.h │ │ │ ├── include │ │ │ │ ├── secp256k1.h │ │ │ │ ├── secp256k1_ecdh.h │ │ │ │ └── secp256k1_recovery.h │ │ │ ├── libsecp256k1.pc.in │ │ │ ├── obj │ │ │ │ └── .gitignore │ │ │ ├── sage │ │ │ │ ├── group_prover.sage │ │ │ │ ├── secp256k1.sage │ │ │ │ └── weierstrass_prover.sage │ │ │ └── src │ │ │ │ ├── asm │ │ │ │ └── field_10x26_arm.s │ │ │ │ ├── basic-config.h │ │ │ │ ├── bench.h │ │ │ │ ├── bench_ecdh.c │ │ │ │ ├── bench_internal.c │ │ │ │ ├── bench_recover.c │ │ │ │ ├── bench_schnorr_verify.c │ │ │ │ ├── bench_sign.c │ │ │ │ ├── bench_verify.c │ │ │ │ ├── ecdsa.h │ │ │ │ ├── ecdsa_impl.h │ │ │ │ ├── eckey.h │ │ │ │ ├── eckey_impl.h │ │ │ │ ├── ecmult.h │ │ │ │ ├── ecmult_const.h │ │ │ │ ├── ecmult_const_impl.h │ │ │ │ ├── ecmult_gen.h │ │ │ │ ├── ecmult_gen_impl.h │ │ │ │ ├── ecmult_impl.h │ │ │ │ ├── field.h │ │ │ │ ├── field_10x26.h │ │ │ │ ├── field_10x26_impl.h │ │ │ │ ├── field_5x52.h │ │ │ │ ├── field_5x52_asm_impl.h │ │ │ │ ├── field_5x52_impl.h │ │ │ │ ├── field_5x52_int128_impl.h │ │ │ │ ├── field_impl.h │ │ │ │ ├── gen_context.c │ │ │ │ ├── group.h │ │ │ │ ├── group_impl.h │ │ │ │ ├── hash.h │ │ │ │ ├── hash_impl.h │ │ │ │ ├── java │ │ │ │ ├── org │ │ │ │ │ └── bitcoin │ │ │ │ │ │ ├── NativeSecp256k1.java │ │ │ │ │ │ ├── NativeSecp256k1Test.java │ │ │ │ │ │ ├── NativeSecp256k1Util.java │ │ │ │ │ │ └── Secp256k1Context.java │ │ │ │ ├── org_bitcoin_NativeSecp256k1.c │ │ │ │ ├── org_bitcoin_NativeSecp256k1.h │ │ │ │ ├── org_bitcoin_Secp256k1Context.c │ │ │ │ └── org_bitcoin_Secp256k1Context.h │ │ │ │ ├── modules │ │ │ │ ├── ecdh │ │ │ │ │ ├── Makefile.am.include │ │ │ │ │ ├── main_impl.h │ │ │ │ │ └── tests_impl.h │ │ │ │ └── recovery │ │ │ │ │ ├── Makefile.am.include │ │ │ │ │ ├── main_impl.h │ │ │ │ │ └── tests_impl.h │ │ │ │ ├── num.h │ │ │ │ ├── num_gmp.h │ │ │ │ ├── num_gmp_impl.h │ │ │ │ ├── num_impl.h │ │ │ │ ├── scalar.h │ │ │ │ ├── scalar_4x64.h │ │ │ │ ├── scalar_4x64_impl.h │ │ │ │ ├── scalar_8x32.h │ │ │ │ ├── scalar_8x32_impl.h │ │ │ │ ├── scalar_impl.h │ │ │ │ ├── scalar_low.h │ │ │ │ ├── scalar_low_impl.h │ │ │ │ ├── secp256k1.c │ │ │ │ ├── testrand.h │ │ │ │ ├── testrand_impl.h │ │ │ │ ├── tests.c │ │ │ │ ├── tests_exhaustive.c │ │ │ │ └── util.h │ │ ├── panic_cb.go │ │ └── secp256.go │ ├── sha3 │ │ ├── keccakf.go │ │ └── sha3.go │ ├── signature_cgo.go │ └── signer.go ├── errors │ ├── codes.go │ ├── errors.go │ └── errors_test.go ├── flogging │ ├── grpclogger.go │ ├── grpclogger_test.go │ ├── logging.go │ └── logging_test.go ├── genesis │ ├── genesis.go │ └── genesis_test.go ├── ledger │ ├── blkstorage │ │ ├── blockstorage.go │ │ └── fsblkstorage │ │ │ ├── block_serialization.go │ │ │ ├── block_serialization_test.go │ │ │ ├── block_stream.go │ │ │ ├── block_stream_test.go │ │ │ ├── blockfile_mgr.go │ │ │ ├── blockfile_mgr_test.go │ │ │ ├── blockfile_rw.go │ │ │ ├── blockfile_scan_test.go │ │ │ ├── blockindex.go │ │ │ ├── blockindex_test.go │ │ │ ├── blocks_itr.go │ │ │ ├── blocks_itr_test.go │ │ │ ├── config.go │ │ │ ├── fs_blockstore.go │ │ │ ├── fs_blockstore_provider.go │ │ │ ├── fs_blockstore_provider_test.go │ │ │ ├── fs_blockstore_test.go │ │ │ └── pkg_test.go │ ├── ledger_interface.go │ ├── testutil │ │ ├── test_helper.go │ │ ├── test_util.go │ │ └── test_util_test.go │ └── util │ │ ├── ioutil.go │ │ ├── ioutil_test.go │ │ ├── leveldbhelper │ │ ├── leveldb_helper.go │ │ ├── leveldb_helper_test.go │ │ ├── leveldb_provider.go │ │ ├── leveldb_provider_test.go │ │ └── pkg_test.go │ │ ├── protobuf_util.go │ │ ├── protobuf_util_test.go │ │ ├── util.go │ │ └── util_test.go ├── localmsp │ ├── signer.go │ └── signer_test.go ├── metadata │ └── metadata.go ├── mocks │ ├── config │ │ ├── channel.go │ │ ├── channel_test.go │ │ ├── orderer.go │ │ └── orderer_test.go │ ├── configtx │ │ ├── configtx.go │ │ └── configtx_test.go │ ├── crypto │ │ ├── localsigner.go │ │ └── localsigner_test.go │ └── ledger │ │ └── queryexecutor.go ├── policies │ ├── implicitmeta.go │ ├── implicitmeta_test.go │ ├── implicitmeta_util.go │ ├── policy.go │ └── policy_test.go ├── tools │ ├── configtxlator │ │ ├── main.go │ │ ├── metadata │ │ │ ├── metadata.go │ │ │ └── metadata_test.go │ │ ├── rest │ │ │ ├── configtxlator_handlers.go │ │ │ ├── configtxlator_handlers_test.go │ │ │ ├── protolator_handlers.go │ │ │ ├── protolator_handlers_test.go │ │ │ └── router.go │ │ ├── sanitycheck │ │ │ ├── sanitycheck.go │ │ │ └── sanitycheck_test.go │ │ └── update │ │ │ ├── update.go │ │ │ └── update_test.go │ ├── cryptogen │ │ ├── ca │ │ │ ├── ca_test.go │ │ │ └── generator.go │ │ ├── csp │ │ │ ├── csp.go │ │ │ └── csp_test.go │ │ ├── main.go │ │ ├── metadata │ │ │ ├── metadata.go │ │ │ └── metadata_test.go │ │ └── msp │ │ │ ├── generator.go │ │ │ └── msp_test.go │ └── protolator │ │ ├── api.go │ │ ├── blackbox_test.go │ │ ├── dynamic.go │ │ ├── dynamic_test.go │ │ ├── json.go │ │ ├── json_test.go │ │ ├── nested.go │ │ ├── nested_test.go │ │ ├── statically_opaque.go │ │ ├── statically_opaque_test.go │ │ ├── testprotos │ │ ├── sample.go │ │ ├── sample.pb.go │ │ └── sample.proto │ │ ├── variably_opaque.go │ │ └── variably_opaque_test.go ├── util │ ├── utils.go │ └── utils_test.go └── viperutil │ ├── config_test.go │ └── config_util.go ├── core └── wallet │ ├── wallet.go │ └── wallet_utils.go ├── devops └── setup-env.sh ├── docs ├── chaincode_interfaces.md ├── getting-started.md ├── images │ └── transet.png ├── update-config.md └── usecases.md ├── events ├── consumer │ ├── adapter.go │ ├── consumer.go │ └── consumer_test.go └── producer │ ├── eventhelper.go │ ├── events.go │ ├── events_test.go │ ├── handler.go │ ├── producer.go │ ├── producer_test.go │ └── register_internal_events.go └── examples ├── asset └── asset.go ├── cat └── cat.go ├── cli_test ├── .env ├── README.md ├── base.yaml ├── channel │ ├── configtx.yaml │ ├── cryptogen.yaml │ ├── genesis.block │ └── mychannel.tx ├── clean-environment.sh ├── docker-compose-2org-4peer-solo.yaml ├── docker-compose-2orgs-4pper-kafka.yaml └── docker-compose.yaml ├── xc └── docker-qtum │ └── test │ └── XCPlugin │ └── send │ ├── setAdmin.sh │ ├── setPlatformName.sh │ ├── setWeight.sh │ ├── start.sh │ ├── stop.sh │ └── voter.sh └── xcDemo └── Xc.go /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TAC - Absorbed In Creating Global Biggest Traceability Public Chain 2 |   We hope to basing on the technology of block chain, adopting unique non-tamper distributed ledger characteristics of the block chain, build the traceability cloud platform. Solve the enterprise's difficulties in information traceability, anti-counterfeit, verification and mobile marketing during commodity production. 3 | 4 |   Circulation and distribution and terminal consumption process through the sub-chain of the landing project and corresponding DAPP application, and provide a fast and efficient cluster of cloud services development for the technical developers, so as to solve the problem of "trusted" for brand enterprises and consumers, and then build a new block chain ecosystem ---Traceability Chain as the future world-selectable internet value transmission protocol, and push forward the practicability and usability of the whole block chain industry. 5 | 6 |   As the most promising block chain ecosystem, it perfectly combines the advantages of Ethereum and Bitshares. 7 | 8 |   Traceability Chain will also constantly and gradually form the block chain economy through the construction of the foundation platform, the design and development of the software and hardware products, the development of various products and the development and iteration of the commercial landing project, improve the industry efficiency, and promote the effective and collaborative development of the society. 9 | 10 | ## White Paper 11 | To learn more about TAC, please read the [White Paper](http://dl.tacblock.com/Traceability_Chain_Whitepaper_eng.pdf)|[白皮书](http://dl.tacblock.com/Traceability_Chain_Whitepaper.pdf). 12 | 13 | ## Official Links 14 | Official website : [ENG](https://tacchain.io) | [中文官网](https://tacchain.cn) 15 | Company News : [ENG](https://blog.tacchain.io) | [中文博客](https://blog.tacchain.cn) -------------------------------------------------------------------------------- /bccsp/aesopts.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package bccsp 18 | 19 | // AES128KeyGenOpts contains options for AES key generation at 128 security level 20 | type AES128KeyGenOpts struct { 21 | Temporary bool 22 | } 23 | 24 | // Algorithm returns the key generation algorithm identifier (to be used). 25 | func (opts *AES128KeyGenOpts) Algorithm() string { 26 | return AES128 27 | } 28 | 29 | // Ephemeral returns true if the key to generate has to be ephemeral, 30 | // false otherwise. 31 | func (opts *AES128KeyGenOpts) Ephemeral() bool { 32 | return opts.Temporary 33 | } 34 | 35 | // AES192KeyGenOpts contains options for AES key generation at 192 security level 36 | type AES192KeyGenOpts struct { 37 | Temporary bool 38 | } 39 | 40 | // Algorithm returns the key generation algorithm identifier (to be used). 41 | func (opts *AES192KeyGenOpts) Algorithm() string { 42 | return AES192 43 | } 44 | 45 | // Ephemeral returns true if the key to generate has to be ephemeral, 46 | // false otherwise. 47 | func (opts *AES192KeyGenOpts) Ephemeral() bool { 48 | return opts.Temporary 49 | } 50 | 51 | // AES256KeyGenOpts contains options for AES key generation at 256 security level 52 | type AES256KeyGenOpts struct { 53 | Temporary bool 54 | } 55 | 56 | // Algorithm returns the key generation algorithm identifier (to be used). 57 | func (opts *AES256KeyGenOpts) Algorithm() string { 58 | return AES256 59 | } 60 | 61 | // Ephemeral returns true if the key to generate has to be ephemeral, 62 | // false otherwise. 63 | func (opts *AES256KeyGenOpts) Ephemeral() bool { 64 | return opts.Temporary 65 | } 66 | -------------------------------------------------------------------------------- /bccsp/ecdsaopts.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package bccsp 18 | 19 | // ECDSAP256KeyGenOpts contains options for ECDSA key generation with curve P-256. 20 | type ECDSAP256KeyGenOpts struct { 21 | Temporary bool 22 | } 23 | 24 | // Algorithm returns the key generation algorithm identifier (to be used). 25 | func (opts *ECDSAP256KeyGenOpts) Algorithm() string { 26 | return ECDSAP256 27 | } 28 | 29 | // Ephemeral returns true if the key to generate has to be ephemeral, 30 | // false otherwise. 31 | func (opts *ECDSAP256KeyGenOpts) Ephemeral() bool { 32 | return opts.Temporary 33 | } 34 | 35 | // ECDSAP384KeyGenOpts contains options for ECDSA key generation with curve P-384. 36 | type ECDSAP384KeyGenOpts struct { 37 | Temporary bool 38 | } 39 | 40 | // Algorithm returns the key generation algorithm identifier (to be used). 41 | func (opts *ECDSAP384KeyGenOpts) Algorithm() string { 42 | return ECDSAP384 43 | } 44 | 45 | // Ephemeral returns true if the key to generate has to be ephemeral, 46 | // false otherwise. 47 | func (opts *ECDSAP384KeyGenOpts) Ephemeral() bool { 48 | return opts.Temporary 49 | } 50 | -------------------------------------------------------------------------------- /bccsp/factory/nopkcs11.go: -------------------------------------------------------------------------------- 1 | // +build nopkcs11 2 | 3 | /* 4 | Copyright IBM Corp. 2017 All Rights Reserved. 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | */ 18 | package factory 19 | 20 | import ( 21 | "fmt" 22 | 23 | "github.com/traceabilitychain/tacchain/bccsp" 24 | ) 25 | 26 | type FactoryOpts struct { 27 | ProviderName string `mapstructure:"default" json:"default" yaml:"Default"` 28 | SwOpts *SwOpts `mapstructure:"SW,omitempty" json:"SW,omitempty" yaml:"SwOpts"` 29 | } 30 | 31 | // InitFactories must be called before using factory interfaces 32 | // It is acceptable to call with config = nil, in which case 33 | // some defaults will get used 34 | // Error is returned only if defaultBCCSP cannot be found 35 | func InitFactories(config *FactoryOpts) error { 36 | factoriesInitOnce.Do(func() { 37 | // Take some precautions on default opts 38 | if config == nil { 39 | config = GetDefaultOpts() 40 | } 41 | 42 | if config.ProviderName == "" { 43 | config.ProviderName = "SW" 44 | } 45 | 46 | if config.SwOpts == nil { 47 | config.SwOpts = GetDefaultOpts().SwOpts 48 | } 49 | 50 | // Initialize factories map 51 | bccspMap = make(map[string]bccsp.BCCSP) 52 | 53 | // Software-Based BCCSP 54 | if config.SwOpts != nil { 55 | f := &SWFactory{} 56 | err := initBCCSP(f, config) 57 | if err != nil { 58 | factoriesInitError = fmt.Errorf("[%s]", err) 59 | } 60 | } 61 | 62 | var ok bool 63 | defaultBCCSP, ok = bccspMap[config.ProviderName] 64 | if !ok { 65 | factoriesInitError = fmt.Errorf("%s\nCould not find default `%s` BCCSP", factoriesInitError, config.ProviderName) 66 | } 67 | }) 68 | 69 | return factoriesInitError 70 | } 71 | 72 | // GetBCCSPFromOpts returns a BCCSP created according to the options passed in input. 73 | func GetBCCSPFromOpts(config *FactoryOpts) (bccsp.BCCSP, error) { 74 | var f BCCSPFactory 75 | switch config.ProviderName { 76 | case "SW": 77 | f = &SWFactory{} 78 | default: 79 | return nil, fmt.Errorf("Could not find BCCSP, no '%s' provider", config.ProviderName) 80 | } 81 | 82 | csp, err := f.Get(config) 83 | if err != nil { 84 | return nil, fmt.Errorf("Could not initialize BCCSP %s [%s]", f.Name(), err) 85 | } 86 | return csp, nil 87 | } 88 | -------------------------------------------------------------------------------- /bccsp/factory/opts.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package factory 17 | 18 | // GetDefaultOpts offers a default implementation for Opts 19 | // returns a new instance every time 20 | func GetDefaultOpts() *FactoryOpts { 21 | return &FactoryOpts{ 22 | ProviderName: "SW", 23 | SwOpts: &SwOpts{ 24 | HashFamily: "SHA2", 25 | SecLevel: 256, 26 | 27 | Ephemeral: true, 28 | }, 29 | } 30 | } 31 | 32 | // FactoryName returns the name of the provider 33 | func (o *FactoryOpts) FactoryName() string { 34 | return o.ProviderName 35 | } 36 | -------------------------------------------------------------------------------- /bccsp/factory/opts_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package factory 17 | 18 | import ( 19 | "testing" 20 | 21 | "github.com/stretchr/testify/assert" 22 | ) 23 | 24 | func TestFactoryOptsFactoryName(t *testing.T) { 25 | assert.Equal(t, GetDefaultOpts().FactoryName(), "SW") 26 | } 27 | -------------------------------------------------------------------------------- /bccsp/factory/pkcs11_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package factory 17 | 18 | import ( 19 | "os" 20 | "testing" 21 | 22 | "github.com/traceabilitychain/tacchain/bccsp/pkcs11" 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestInitFactories(t *testing.T) { 27 | // Reset errors from previous negative test runs 28 | factoriesInitError = nil 29 | 30 | err := InitFactories(nil) 31 | assert.NoError(t, err) 32 | } 33 | 34 | func TestSetFactories(t *testing.T) { 35 | err := setFactories(nil) 36 | assert.NoError(t, err) 37 | 38 | err = setFactories(&FactoryOpts{}) 39 | assert.NoError(t, err) 40 | } 41 | 42 | func TestSetFactoriesInvalidArgs(t *testing.T) { 43 | err := setFactories(&FactoryOpts{ 44 | ProviderName: "SW", 45 | SwOpts: &SwOpts{}, 46 | }) 47 | assert.Error(t, err) 48 | assert.Contains(t, err.Error(), "Failed initializing SW.BCCSP") 49 | 50 | err = setFactories(&FactoryOpts{ 51 | ProviderName: "PKCS11", 52 | Pkcs11Opts: &pkcs11.PKCS11Opts{}, 53 | }) 54 | assert.Error(t, err) 55 | assert.Contains(t, err.Error(), "Failed initializing PKCS11.BCCSP") 56 | } 57 | 58 | func TestGetBCCSPFromOpts(t *testing.T) { 59 | opts := GetDefaultOpts() 60 | opts.SwOpts.FileKeystore = &FileKeystoreOpts{KeyStorePath: os.TempDir()} 61 | opts.SwOpts.Ephemeral = false 62 | csp, err := GetBCCSPFromOpts(opts) 63 | assert.NoError(t, err) 64 | assert.NotNil(t, csp) 65 | 66 | lib, pin, label := pkcs11.FindPKCS11Lib() 67 | csp, err = GetBCCSPFromOpts(&FactoryOpts{ 68 | ProviderName: "PKCS11", 69 | Pkcs11Opts: &pkcs11.PKCS11Opts{ 70 | SecLevel: 256, 71 | HashFamily: "SHA2", 72 | Ephemeral: true, 73 | Library: lib, 74 | Pin: pin, 75 | Label: label, 76 | }, 77 | }) 78 | assert.NoError(t, err) 79 | assert.NotNil(t, csp) 80 | 81 | csp, err = GetBCCSPFromOpts(&FactoryOpts{ 82 | ProviderName: "BadName", 83 | }) 84 | assert.Error(t, err) 85 | assert.Contains(t, err.Error(), "Could not find BCCSP, no 'BadName' provider") 86 | assert.Nil(t, csp) 87 | } 88 | -------------------------------------------------------------------------------- /bccsp/factory/pkcs11factory.go: -------------------------------------------------------------------------------- 1 | // +build !nopkcs11 2 | 3 | /* 4 | Copyright IBM Corp. 2016 All Rights Reserved. 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | */ 18 | package factory 19 | 20 | import ( 21 | "errors" 22 | "fmt" 23 | 24 | "github.com/traceabilitychain/tacchain/bccsp" 25 | "github.com/traceabilitychain/tacchain/bccsp/pkcs11" 26 | "github.com/traceabilitychain/tacchain/bccsp/sw" 27 | ) 28 | 29 | const ( 30 | // PKCS11BasedFactoryName is the name of the factory of the hsm-based BCCSP implementation 31 | PKCS11BasedFactoryName = "PKCS11" 32 | ) 33 | 34 | // PKCS11Factory is the factory of the HSM-based BCCSP. 35 | type PKCS11Factory struct{} 36 | 37 | // Name returns the name of this factory 38 | func (f *PKCS11Factory) Name() string { 39 | return PKCS11BasedFactoryName 40 | } 41 | 42 | // Get returns an instance of BCCSP using Opts. 43 | func (f *PKCS11Factory) Get(config *FactoryOpts) (bccsp.BCCSP, error) { 44 | // Validate arguments 45 | if config == nil || config.Pkcs11Opts == nil { 46 | return nil, errors.New("Invalid config. It must not be nil.") 47 | } 48 | 49 | p11Opts := config.Pkcs11Opts 50 | 51 | //TODO: PKCS11 does not need a keystore, but we have not migrated all of PKCS11 BCCSP to PKCS11 yet 52 | var ks bccsp.KeyStore 53 | if p11Opts.Ephemeral == true { 54 | ks = sw.NewDummyKeyStore() 55 | } else if p11Opts.FileKeystore != nil { 56 | fks, err := sw.NewFileBasedKeyStore(nil, p11Opts.FileKeystore.KeyStorePath, false) 57 | if err != nil { 58 | return nil, fmt.Errorf("Failed to initialize software key store: %s", err) 59 | } 60 | ks = fks 61 | } else { 62 | // Default to DummyKeystore 63 | ks = sw.NewDummyKeyStore() 64 | } 65 | return pkcs11.New(*p11Opts, ks) 66 | } 67 | -------------------------------------------------------------------------------- /bccsp/factory/pkcs11factory_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package factory 17 | 18 | import ( 19 | "os" 20 | "testing" 21 | 22 | "github.com/traceabilitychain/tacchain/bccsp/pkcs11" 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestPKCS11FactoryName(t *testing.T) { 27 | f := &PKCS11Factory{} 28 | assert.Equal(t, f.Name(), PKCS11BasedFactoryName) 29 | } 30 | 31 | func TestPKCS11FactoryGetInvalidArgs(t *testing.T) { 32 | f := &PKCS11Factory{} 33 | 34 | _, err := f.Get(nil) 35 | assert.Error(t, err, "Invalid config. It must not be nil.") 36 | 37 | _, err = f.Get(&FactoryOpts{}) 38 | assert.Error(t, err, "Invalid config. It must not be nil.") 39 | 40 | opts := &FactoryOpts{ 41 | Pkcs11Opts: &pkcs11.PKCS11Opts{}, 42 | } 43 | _, err = f.Get(opts) 44 | assert.Error(t, err, "CSP:500 - Failed initializing configuration at [0,]") 45 | } 46 | 47 | func TestPKCS11FactoryGet(t *testing.T) { 48 | f := &PKCS11Factory{} 49 | lib, pin, label := pkcs11.FindPKCS11Lib() 50 | 51 | opts := &FactoryOpts{ 52 | Pkcs11Opts: &pkcs11.PKCS11Opts{ 53 | SecLevel: 256, 54 | HashFamily: "SHA2", 55 | Library: lib, 56 | Pin: pin, 57 | Label: label, 58 | }, 59 | } 60 | csp, err := f.Get(opts) 61 | assert.NoError(t, err) 62 | assert.NotNil(t, csp) 63 | 64 | opts = &FactoryOpts{ 65 | Pkcs11Opts: &pkcs11.PKCS11Opts{ 66 | SecLevel: 256, 67 | HashFamily: "SHA2", 68 | FileKeystore: &pkcs11.FileKeystoreOpts{KeyStorePath: os.TempDir()}, 69 | Library: lib, 70 | Pin: pin, 71 | Label: label, 72 | }, 73 | } 74 | csp, err = f.Get(opts) 75 | assert.NoError(t, err) 76 | assert.NotNil(t, csp) 77 | 78 | opts = &FactoryOpts{ 79 | Pkcs11Opts: &pkcs11.PKCS11Opts{ 80 | SecLevel: 256, 81 | HashFamily: "SHA2", 82 | Ephemeral: true, 83 | Library: lib, 84 | Pin: pin, 85 | Label: label, 86 | }, 87 | } 88 | csp, err = f.Get(opts) 89 | assert.NoError(t, err) 90 | assert.NotNil(t, csp) 91 | } 92 | -------------------------------------------------------------------------------- /bccsp/factory/swfactory_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package factory 17 | 18 | import ( 19 | "os" 20 | "testing" 21 | 22 | "github.com/stretchr/testify/assert" 23 | ) 24 | 25 | func TestSWFactoryName(t *testing.T) { 26 | f := &SWFactory{} 27 | assert.Equal(t, f.Name(), SoftwareBasedFactoryName) 28 | } 29 | 30 | func TestSWFactoryGetInvalidArgs(t *testing.T) { 31 | f := &SWFactory{} 32 | 33 | _, err := f.Get(nil) 34 | assert.Error(t, err, "Invalid config. It must not be nil.") 35 | 36 | _, err = f.Get(&FactoryOpts{}) 37 | assert.Error(t, err, "Invalid config. It must not be nil.") 38 | 39 | opts := &FactoryOpts{ 40 | SwOpts: &SwOpts{}, 41 | } 42 | _, err = f.Get(opts) 43 | assert.Error(t, err, "CSP:500 - Failed initializing configuration at [0,]") 44 | } 45 | 46 | func TestSWFactoryGet(t *testing.T) { 47 | f := &SWFactory{} 48 | 49 | opts := &FactoryOpts{ 50 | SwOpts: &SwOpts{ 51 | SecLevel: 256, 52 | HashFamily: "SHA2", 53 | }, 54 | } 55 | csp, err := f.Get(opts) 56 | assert.NoError(t, err) 57 | assert.NotNil(t, csp) 58 | 59 | opts = &FactoryOpts{ 60 | SwOpts: &SwOpts{ 61 | SecLevel: 256, 62 | HashFamily: "SHA2", 63 | FileKeystore: &FileKeystoreOpts{KeyStorePath: os.TempDir()}, 64 | }, 65 | } 66 | csp, err = f.Get(opts) 67 | assert.NoError(t, err) 68 | assert.NotNil(t, csp) 69 | 70 | } 71 | -------------------------------------------------------------------------------- /bccsp/hashopts.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package bccsp 18 | 19 | import "fmt" 20 | 21 | // SHA256Opts contains options relating to SHA-256. 22 | type SHA256Opts struct { 23 | } 24 | 25 | // Algorithm returns the hash algorithm identifier (to be used). 26 | func (opts *SHA256Opts) Algorithm() string { 27 | return SHA256 28 | } 29 | 30 | // SHA384Opts contains options relating to SHA-384. 31 | type SHA384Opts struct { 32 | } 33 | 34 | // Algorithm returns the hash algorithm identifier (to be used). 35 | func (opts *SHA384Opts) Algorithm() string { 36 | return SHA384 37 | } 38 | 39 | // SHA3_256Opts contains options relating to SHA3-256. 40 | type SHA3_256Opts struct { 41 | } 42 | 43 | // Algorithm returns the hash algorithm identifier (to be used). 44 | func (opts *SHA3_256Opts) Algorithm() string { 45 | return SHA3_256 46 | } 47 | 48 | // SHA3_384Opts contains options relating to SHA3-384. 49 | type SHA3_384Opts struct { 50 | } 51 | 52 | // Algorithm returns the hash algorithm identifier (to be used). 53 | func (opts *SHA3_384Opts) Algorithm() string { 54 | return SHA3_384 55 | } 56 | 57 | // GetHashOpt returns the HashOpts corresponding to the passed hash function 58 | func GetHashOpt(hashFunction string) (HashOpts, error) { 59 | switch hashFunction { 60 | case SHA256: 61 | return &SHA256Opts{}, nil 62 | case SHA384: 63 | return &SHA384Opts{}, nil 64 | case SHA3_256: 65 | return &SHA3_256Opts{}, nil 66 | case SHA3_384: 67 | return &SHA3_384Opts{}, nil 68 | } 69 | return nil, fmt.Errorf("hash function not recognized [%s]", hashFunction) 70 | } 71 | -------------------------------------------------------------------------------- /bccsp/keystore.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package bccsp 17 | 18 | // KeyStore represents a storage system for cryptographic keys. 19 | // It allows to store and retrieve bccsp.Key objects. 20 | // The KeyStore can be read only, in that case StoreKey will return 21 | // an error. 22 | type KeyStore interface { 23 | 24 | // ReadOnly returns true if this KeyStore is read only, false otherwise. 25 | // If ReadOnly is true then StoreKey will fail. 26 | ReadOnly() bool 27 | 28 | // GetKey returns a key object whose SKI is the one passed. 29 | GetKey(ski []byte) (k Key, err error) 30 | 31 | // StoreKey stores the key k in this KeyStore. 32 | // If this KeyStore is read only then the method will fail. 33 | StoreKey(k Key) (err error) 34 | } 35 | -------------------------------------------------------------------------------- /bccsp/pkcs11/ecdsa_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package pkcs11 18 | 19 | import ( 20 | "math/big" 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestUnmarshalECDSASignature(t *testing.T) { 27 | _, _, err := unmarshalECDSASignature(nil) 28 | assert.Error(t, err) 29 | assert.Contains(t, err.Error(), "Failed unmashalling signature [") 30 | 31 | _, _, err = unmarshalECDSASignature([]byte{}) 32 | assert.Error(t, err) 33 | assert.Contains(t, err.Error(), "Failed unmashalling signature [") 34 | 35 | _, _, err = unmarshalECDSASignature([]byte{0}) 36 | assert.Error(t, err) 37 | assert.Contains(t, err.Error(), "Failed unmashalling signature [") 38 | 39 | sigma, err := marshalECDSASignature(big.NewInt(-1), big.NewInt(1)) 40 | assert.NoError(t, err) 41 | _, _, err = unmarshalECDSASignature(sigma) 42 | assert.Error(t, err) 43 | assert.Contains(t, err.Error(), "Invalid signature. R must be larger than zero") 44 | 45 | sigma, err = marshalECDSASignature(big.NewInt(0), big.NewInt(1)) 46 | assert.NoError(t, err) 47 | _, _, err = unmarshalECDSASignature(sigma) 48 | assert.Error(t, err) 49 | assert.Contains(t, err.Error(), "Invalid signature. R must be larger than zero") 50 | 51 | sigma, err = marshalECDSASignature(big.NewInt(1), big.NewInt(0)) 52 | assert.NoError(t, err) 53 | _, _, err = unmarshalECDSASignature(sigma) 54 | assert.Error(t, err) 55 | assert.Contains(t, err.Error(), "Invalid signature. S must be larger than zero") 56 | 57 | sigma, err = marshalECDSASignature(big.NewInt(1), big.NewInt(-1)) 58 | assert.NoError(t, err) 59 | _, _, err = unmarshalECDSASignature(sigma) 60 | assert.Error(t, err) 61 | assert.Contains(t, err.Error(), "Invalid signature. S must be larger than zero") 62 | 63 | sigma, err = marshalECDSASignature(big.NewInt(1), big.NewInt(1)) 64 | assert.NoError(t, err) 65 | R, S, err := unmarshalECDSASignature(sigma) 66 | assert.NoError(t, err) 67 | assert.Equal(t, big.NewInt(1), R) 68 | assert.Equal(t, big.NewInt(1), S) 69 | } 70 | -------------------------------------------------------------------------------- /bccsp/rsaopts.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package bccsp 18 | 19 | // RSA1024KeyGenOpts contains options for RSA key generation at 1024 security. 20 | type RSA1024KeyGenOpts struct { 21 | Temporary bool 22 | } 23 | 24 | // Algorithm returns the key generation algorithm identifier (to be used). 25 | func (opts *RSA1024KeyGenOpts) Algorithm() string { 26 | return RSA1024 27 | } 28 | 29 | // Ephemeral returns true if the key to generate has to be ephemeral, 30 | // false otherwise. 31 | func (opts *RSA1024KeyGenOpts) Ephemeral() bool { 32 | return opts.Temporary 33 | } 34 | 35 | // RSA2048KeyGenOpts contains options for RSA key generation at 2048 security. 36 | type RSA2048KeyGenOpts struct { 37 | Temporary bool 38 | } 39 | 40 | // Algorithm returns the key generation algorithm identifier (to be used). 41 | func (opts *RSA2048KeyGenOpts) Algorithm() string { 42 | return RSA2048 43 | } 44 | 45 | // Ephemeral returns true if the key to generate has to be ephemeral, 46 | // false otherwise. 47 | func (opts *RSA2048KeyGenOpts) Ephemeral() bool { 48 | return opts.Temporary 49 | } 50 | 51 | // RSA3072KeyGenOpts contains options for RSA key generation at 3072 security. 52 | type RSA3072KeyGenOpts struct { 53 | Temporary bool 54 | } 55 | 56 | // Algorithm returns the key generation algorithm identifier (to be used). 57 | func (opts *RSA3072KeyGenOpts) Algorithm() string { 58 | return RSA3072 59 | } 60 | 61 | // Ephemeral returns true if the key to generate has to be ephemeral, 62 | // false otherwise. 63 | func (opts *RSA3072KeyGenOpts) Ephemeral() bool { 64 | return opts.Temporary 65 | } 66 | 67 | // RSA4096KeyGenOpts contains options for RSA key generation at 4096 security. 68 | type RSA4096KeyGenOpts struct { 69 | Temporary bool 70 | } 71 | 72 | // Algorithm returns the key generation algorithm identifier (to be used). 73 | func (opts *RSA4096KeyGenOpts) Algorithm() string { 74 | return RSA4096 75 | } 76 | 77 | // Ephemeral returns true if the key to generate has to be ephemeral, 78 | // false otherwise. 79 | func (opts *RSA4096KeyGenOpts) Ephemeral() bool { 80 | return opts.Temporary 81 | } 82 | -------------------------------------------------------------------------------- /bccsp/sw/aeskey.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package sw 17 | 18 | import ( 19 | "errors" 20 | 21 | "crypto/sha256" 22 | 23 | "github.com/traceabilitychain/tacchain/bccsp" 24 | ) 25 | 26 | type aesPrivateKey struct { 27 | privKey []byte 28 | exportable bool 29 | } 30 | 31 | // Bytes converts this key to its byte representation, 32 | // if this operation is allowed. 33 | func (k *aesPrivateKey) Bytes() (raw []byte, err error) { 34 | if k.exportable { 35 | return k.privKey, nil 36 | } 37 | 38 | return nil, errors.New("Not supported.") 39 | } 40 | 41 | // SKI returns the subject key identifier of this key. 42 | func (k *aesPrivateKey) SKI() (ski []byte) { 43 | hash := sha256.New() 44 | hash.Write([]byte{0x01}) 45 | hash.Write(k.privKey) 46 | return hash.Sum(nil) 47 | } 48 | 49 | // Symmetric returns true if this key is a symmetric key, 50 | // false if this key is asymmetric 51 | func (k *aesPrivateKey) Symmetric() bool { 52 | return true 53 | } 54 | 55 | // Private returns true if this key is a private key, 56 | // false otherwise. 57 | func (k *aesPrivateKey) Private() bool { 58 | return true 59 | } 60 | 61 | // PublicKey returns the corresponding public key part of an asymmetric public/private key pair. 62 | // This method returns an error in symmetric key schemes. 63 | func (k *aesPrivateKey) PublicKey() (bccsp.Key, error) { 64 | return nil, errors.New("Cannot call this method on a symmetric key.") 65 | } 66 | -------------------------------------------------------------------------------- /bccsp/sw/conf.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package sw 17 | 18 | import ( 19 | "crypto/elliptic" 20 | "crypto/sha256" 21 | "crypto/sha512" 22 | "fmt" 23 | "hash" 24 | 25 | "golang.org/x/crypto/sha3" 26 | ) 27 | 28 | type config struct { 29 | ellipticCurve elliptic.Curve 30 | hashFunction func() hash.Hash 31 | aesBitLength int 32 | rsaBitLength int 33 | } 34 | 35 | func (conf *config) setSecurityLevel(securityLevel int, hashFamily string) (err error) { 36 | switch hashFamily { 37 | case "SHA2": 38 | err = conf.setSecurityLevelSHA2(securityLevel) 39 | case "SHA3": 40 | err = conf.setSecurityLevelSHA3(securityLevel) 41 | default: 42 | err = fmt.Errorf("Hash Family not supported [%s]", hashFamily) 43 | } 44 | return 45 | } 46 | 47 | func (conf *config) setSecurityLevelSHA2(level int) (err error) { 48 | switch level { 49 | case 256: 50 | conf.ellipticCurve = elliptic.P256() 51 | conf.hashFunction = sha256.New 52 | conf.rsaBitLength = 2048 53 | conf.aesBitLength = 32 54 | case 384: 55 | conf.ellipticCurve = elliptic.P384() 56 | conf.hashFunction = sha512.New384 57 | conf.rsaBitLength = 3072 58 | conf.aesBitLength = 32 59 | default: 60 | err = fmt.Errorf("Security level not supported [%d]", level) 61 | } 62 | return 63 | } 64 | 65 | func (conf *config) setSecurityLevelSHA3(level int) (err error) { 66 | switch level { 67 | case 256: 68 | conf.ellipticCurve = elliptic.P256() 69 | conf.hashFunction = sha3.New256 70 | conf.rsaBitLength = 2048 71 | conf.aesBitLength = 32 72 | case 384: 73 | conf.ellipticCurve = elliptic.P384() 74 | conf.hashFunction = sha3.New384 75 | conf.rsaBitLength = 3072 76 | conf.aesBitLength = 32 77 | default: 78 | err = fmt.Errorf("Security level not supported [%d]", level) 79 | } 80 | return 81 | } 82 | -------------------------------------------------------------------------------- /bccsp/sw/dummyks.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package sw 17 | 18 | import ( 19 | "errors" 20 | 21 | "github.com/traceabilitychain/tacchain/bccsp" 22 | ) 23 | 24 | // NewDummyKeyStore instantiate a dummy key store 25 | // that neither loads nor stores keys 26 | func NewDummyKeyStore() bccsp.KeyStore { 27 | return &dummyKeyStore{} 28 | } 29 | 30 | // dummyKeyStore is a read-only KeyStore that neither loads nor stores keys. 31 | type dummyKeyStore struct { 32 | } 33 | 34 | // ReadOnly returns true if this KeyStore is read only, false otherwise. 35 | // If ReadOnly is true then StoreKey will fail. 36 | func (ks *dummyKeyStore) ReadOnly() bool { 37 | return true 38 | } 39 | 40 | // GetKey returns a key object whose SKI is the one passed. 41 | func (ks *dummyKeyStore) GetKey(ski []byte) (k bccsp.Key, err error) { 42 | return nil, errors.New("Key not found. This is a dummy KeyStore") 43 | } 44 | 45 | // StoreKey stores the key k in this KeyStore. 46 | // If this KeyStore is read only then the method will fail. 47 | func (ks *dummyKeyStore) StoreKey(k bccsp.Key) (err error) { 48 | return errors.New("Cannot store key. This is a dummy read-only KeyStore") 49 | } 50 | -------------------------------------------------------------------------------- /bccsp/sw/dummyks_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package sw 17 | 18 | import ( 19 | "testing" 20 | 21 | "github.com/traceabilitychain/tacchain/bccsp/mocks" 22 | "github.com/stretchr/testify/assert" 23 | ) 24 | 25 | func TestNewDummyKeyStore(t *testing.T) { 26 | ks := NewDummyKeyStore() 27 | assert.NotNil(t, ks) 28 | } 29 | 30 | func TestDummyKeyStore_GetKey(t *testing.T) { 31 | ks := NewDummyKeyStore() 32 | _, err := ks.GetKey([]byte{0, 1, 2, 3, 4}) 33 | assert.Error(t, err) 34 | } 35 | 36 | func TestDummyKeyStore_ReadOnly(t *testing.T) { 37 | ks := NewDummyKeyStore() 38 | assert.True(t, ks.ReadOnly()) 39 | } 40 | 41 | func TestDummyKeyStore_StoreKey(t *testing.T) { 42 | ks := NewDummyKeyStore() 43 | err := ks.StoreKey(&mocks.MockKey{}) 44 | assert.Error(t, err) 45 | } 46 | -------------------------------------------------------------------------------- /bccsp/sw/enc_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package sw 18 | 19 | import ( 20 | "errors" 21 | "reflect" 22 | "testing" 23 | 24 | mocks2 "github.com/traceabilitychain/tacchain/bccsp/mocks" 25 | "github.com/traceabilitychain/tacchain/bccsp/sw/mocks" 26 | "github.com/stretchr/testify/assert" 27 | ) 28 | 29 | func TestEncrypt(t *testing.T) { 30 | expectedKey := &mocks2.MockKey{} 31 | expectedPlaintext := []byte{1, 2, 3, 4} 32 | expectedOpts := &mocks2.EncrypterOpts{} 33 | expectedCiphertext := []byte{0, 1, 2, 3, 4} 34 | expectedErr := errors.New("no error") 35 | 36 | encryptors := make(map[reflect.Type]Encryptor) 37 | encryptors[reflect.TypeOf(&mocks2.MockKey{})] = &mocks.Encryptor{ 38 | KeyArg: expectedKey, 39 | PlaintextArg: expectedPlaintext, 40 | OptsArg: expectedOpts, 41 | EncValue: expectedCiphertext, 42 | EncErr: expectedErr, 43 | } 44 | 45 | csp := impl{encryptors: encryptors} 46 | 47 | ct, err := csp.Encrypt(expectedKey, expectedPlaintext, expectedOpts) 48 | assert.Equal(t, expectedCiphertext, ct) 49 | assert.Equal(t, expectedErr, err) 50 | } 51 | -------------------------------------------------------------------------------- /bccsp/sw/fileks_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package sw 17 | 18 | import ( 19 | "fmt" 20 | "os" 21 | "path/filepath" 22 | "testing" 23 | ) 24 | 25 | func TestInvalidStoreKey(t *testing.T) { 26 | ks, err := NewFileBasedKeyStore(nil, filepath.Join(os.TempDir(), "bccspks"), false) 27 | if err != nil { 28 | fmt.Printf("Failed initiliazing KeyStore [%s]", err) 29 | os.Exit(-1) 30 | } 31 | 32 | err = ks.StoreKey(nil) 33 | if err == nil { 34 | t.Fatal("Error should be different from nil in this case") 35 | } 36 | 37 | err = ks.StoreKey(&ecdsaPrivateKey{nil}) 38 | if err == nil { 39 | t.Fatal("Error should be different from nil in this case") 40 | } 41 | 42 | err = ks.StoreKey(&ecdsaPublicKey{nil}) 43 | if err == nil { 44 | t.Fatal("Error should be different from nil in this case") 45 | } 46 | 47 | err = ks.StoreKey(&rsaPublicKey{nil}) 48 | if err == nil { 49 | t.Fatal("Error should be different from nil in this case") 50 | } 51 | 52 | err = ks.StoreKey(&rsaPrivateKey{nil}) 53 | if err == nil { 54 | t.Fatal("Error should be different from nil in this case") 55 | } 56 | 57 | err = ks.StoreKey(&aesPrivateKey{nil, false}) 58 | if err == nil { 59 | t.Fatal("Error should be different from nil in this case") 60 | } 61 | 62 | err = ks.StoreKey(&aesPrivateKey{nil, true}) 63 | if err == nil { 64 | t.Fatal("Error should be different from nil in this case") 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /bccsp/sw/hash.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package sw 18 | 19 | import ( 20 | "hash" 21 | 22 | "github.com/traceabilitychain/tacchain/bccsp" 23 | ) 24 | 25 | type hasher struct { 26 | hash func() hash.Hash 27 | } 28 | 29 | func (c *hasher) Hash(msg []byte, opts bccsp.HashOpts) (hash []byte, err error) { 30 | h := c.hash() 31 | h.Write(msg) 32 | return h.Sum(nil), nil 33 | } 34 | 35 | func (c *hasher) GetHash(opts bccsp.HashOpts) (h hash.Hash, err error) { 36 | return c.hash(), nil 37 | } 38 | -------------------------------------------------------------------------------- /bccsp/sw/keygen.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package sw 18 | 19 | import ( 20 | "crypto/ecdsa" 21 | "crypto/elliptic" 22 | "crypto/rand" 23 | "crypto/rsa" 24 | "fmt" 25 | 26 | "github.com/traceabilitychain/tacchain/bccsp" 27 | ) 28 | 29 | type ecdsaKeyGenerator struct { 30 | curve elliptic.Curve 31 | } 32 | 33 | func (kg *ecdsaKeyGenerator) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) { 34 | privKey, err := ecdsa.GenerateKey(kg.curve, rand.Reader) 35 | if err != nil { 36 | return nil, fmt.Errorf("Failed generating ECDSA key for [%v]: [%s]", kg.curve, err) 37 | } 38 | 39 | return &ecdsaPrivateKey{privKey}, nil 40 | } 41 | 42 | type aesKeyGenerator struct { 43 | length int 44 | } 45 | 46 | func (kg *aesKeyGenerator) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) { 47 | lowLevelKey, err := GetRandomBytes(int(kg.length)) 48 | if err != nil { 49 | return nil, fmt.Errorf("Failed generating AES %d key [%s]", kg.length, err) 50 | } 51 | 52 | return &aesPrivateKey{lowLevelKey, false}, nil 53 | } 54 | 55 | type rsaKeyGenerator struct { 56 | length int 57 | } 58 | 59 | func (kg *rsaKeyGenerator) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) { 60 | lowLevelKey, err := rsa.GenerateKey(rand.Reader, int(kg.length)) 61 | 62 | if err != nil { 63 | return nil, fmt.Errorf("Failed generating RSA %d key [%s]", kg.length, err) 64 | } 65 | 66 | return &rsaPrivateKey{lowLevelKey}, nil 67 | } 68 | -------------------------------------------------------------------------------- /bccsp/sw/rsa.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package sw 18 | 19 | import ( 20 | "crypto/rand" 21 | "crypto/rsa" 22 | "errors" 23 | "fmt" 24 | 25 | "github.com/traceabilitychain/tacchain/bccsp" 26 | ) 27 | 28 | type rsaSigner struct{} 29 | 30 | func (s *rsaSigner) Sign(k bccsp.Key, digest []byte, opts bccsp.SignerOpts) (signature []byte, err error) { 31 | if opts == nil { 32 | return nil, errors.New("Invalid options. Must be different from nil.") 33 | } 34 | 35 | return k.(*rsaPrivateKey).privKey.Sign(rand.Reader, digest, opts) 36 | } 37 | 38 | type rsaPrivateKeyVerifier struct{} 39 | 40 | func (v *rsaPrivateKeyVerifier) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (valid bool, err error) { 41 | if opts == nil { 42 | return false, errors.New("Invalid options. It must not be nil.") 43 | } 44 | switch opts.(type) { 45 | case *rsa.PSSOptions: 46 | err := rsa.VerifyPSS(&(k.(*rsaPrivateKey).privKey.PublicKey), 47 | (opts.(*rsa.PSSOptions)).Hash, 48 | digest, signature, opts.(*rsa.PSSOptions)) 49 | 50 | return err == nil, err 51 | default: 52 | return false, fmt.Errorf("Opts type not recognized [%s]", opts) 53 | } 54 | } 55 | 56 | type rsaPublicKeyKeyVerifier struct{} 57 | 58 | func (v *rsaPublicKeyKeyVerifier) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (valid bool, err error) { 59 | if opts == nil { 60 | return false, errors.New("Invalid options. It must not be nil.") 61 | } 62 | switch opts.(type) { 63 | case *rsa.PSSOptions: 64 | err := rsa.VerifyPSS(k.(*rsaPublicKey).pubKey, 65 | (opts.(*rsa.PSSOptions)).Hash, 66 | digest, signature, opts.(*rsa.PSSOptions)) 67 | 68 | return err == nil, err 69 | default: 70 | return false, fmt.Errorf("Opts type not recognized [%s]", opts) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /bccsp/sw/sign_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package sw 18 | 19 | import ( 20 | "errors" 21 | "reflect" 22 | "testing" 23 | 24 | mocks2 "github.com/traceabilitychain/tacchain/bccsp/mocks" 25 | "github.com/traceabilitychain/tacchain/bccsp/sw/mocks" 26 | "github.com/stretchr/testify/assert" 27 | ) 28 | 29 | func TestSign(t *testing.T) { 30 | expectedKey := &mocks2.MockKey{} 31 | expectetDigest := []byte{1, 2, 3, 4} 32 | expectedOpts := &mocks2.SignerOpts{} 33 | expectetValue := []byte{0, 1, 2, 3, 4} 34 | expectedErr := errors.New("Expected Error") 35 | 36 | signers := make(map[reflect.Type]Signer) 37 | signers[reflect.TypeOf(&mocks2.MockKey{})] = &mocks.Signer{ 38 | KeyArg: expectedKey, 39 | DigestArg: expectetDigest, 40 | OptsArg: expectedOpts, 41 | Value: expectetValue, 42 | Err: nil, 43 | } 44 | csp := impl{signers: signers} 45 | value, err := csp.Sign(expectedKey, expectetDigest, expectedOpts) 46 | assert.Equal(t, expectetValue, value) 47 | assert.Nil(t, err) 48 | 49 | signers = make(map[reflect.Type]Signer) 50 | signers[reflect.TypeOf(&mocks2.MockKey{})] = &mocks.Signer{ 51 | KeyArg: expectedKey, 52 | DigestArg: expectetDigest, 53 | OptsArg: expectedOpts, 54 | Value: nil, 55 | Err: expectedErr, 56 | } 57 | csp = impl{signers: signers} 58 | value, err = csp.Sign(expectedKey, expectetDigest, expectedOpts) 59 | assert.Nil(t, value) 60 | assert.Contains(t, err.Error(), expectedErr.Error()) 61 | } 62 | -------------------------------------------------------------------------------- /bccsp/sw/verify_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package sw 18 | 19 | import ( 20 | "errors" 21 | "reflect" 22 | "testing" 23 | 24 | mocks2 "github.com/traceabilitychain/tacchain/bccsp/mocks" 25 | "github.com/traceabilitychain/tacchain/bccsp/sw/mocks" 26 | "github.com/stretchr/testify/assert" 27 | ) 28 | 29 | func TestVerify(t *testing.T) { 30 | expectedKey := &mocks2.MockKey{} 31 | expectetSignature := []byte{1, 2, 3, 4, 5} 32 | expectetDigest := []byte{1, 2, 3, 4} 33 | expectedOpts := &mocks2.SignerOpts{} 34 | expectetValue := true 35 | expectedErr := errors.New("Expected Error") 36 | 37 | verifiers := make(map[reflect.Type]Verifier) 38 | verifiers[reflect.TypeOf(&mocks2.MockKey{})] = &mocks.Verifier{ 39 | KeyArg: expectedKey, 40 | SignatureArg: expectetSignature, 41 | DigestArg: expectetDigest, 42 | OptsArg: expectedOpts, 43 | Value: expectetValue, 44 | Err: nil, 45 | } 46 | csp := impl{verifiers: verifiers} 47 | value, err := csp.Verify(expectedKey, expectetSignature, expectetDigest, expectedOpts) 48 | assert.Equal(t, expectetValue, value) 49 | assert.Nil(t, err) 50 | 51 | verifiers = make(map[reflect.Type]Verifier) 52 | verifiers[reflect.TypeOf(&mocks2.MockKey{})] = &mocks.Verifier{ 53 | KeyArg: expectedKey, 54 | SignatureArg: expectetSignature, 55 | DigestArg: expectetDigest, 56 | OptsArg: expectedOpts, 57 | Value: false, 58 | Err: expectedErr, 59 | } 60 | csp = impl{verifiers: verifiers} 61 | value, err = csp.Verify(expectedKey, expectetSignature, expectetDigest, expectedOpts) 62 | assert.False(t, value) 63 | assert.Contains(t, err.Error(), expectedErr.Error()) 64 | } 65 | -------------------------------------------------------------------------------- /bccsp/utils/errs.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package utils 18 | 19 | // ErrToString converts and error to a string. If the error is nil, it returns the string "" 20 | func ErrToString(err error) string { 21 | if err != nil { 22 | return err.Error() 23 | } 24 | 25 | return "" 26 | } 27 | -------------------------------------------------------------------------------- /bccsp/utils/errs_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package utils 18 | 19 | import ( 20 | "errors" 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestErrToString(t *testing.T) { 27 | assert.Equal(t, ErrToString(errors.New("error")), "error") 28 | 29 | assert.Equal(t, ErrToString(nil), "") 30 | 31 | } 32 | -------------------------------------------------------------------------------- /bccsp/utils/io.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package utils 18 | 19 | import ( 20 | "io" 21 | "os" 22 | ) 23 | 24 | // DirMissingOrEmpty checks is a directory is missin or empty 25 | func DirMissingOrEmpty(path string) (bool, error) { 26 | dirExists, err := DirExists(path) 27 | if err != nil { 28 | return false, err 29 | } 30 | if !dirExists { 31 | return true, nil 32 | } 33 | 34 | dirEmpty, err := DirEmpty(path) 35 | if err != nil { 36 | return false, err 37 | } 38 | if dirEmpty { 39 | return true, nil 40 | } 41 | return false, nil 42 | } 43 | 44 | // DirExists checks if a directory exists 45 | func DirExists(path string) (bool, error) { 46 | _, err := os.Stat(path) 47 | if err == nil { 48 | return true, nil 49 | } 50 | if os.IsNotExist(err) { 51 | return false, nil 52 | } 53 | return false, err 54 | } 55 | 56 | // DirEmpty checks if a directory is empty 57 | func DirEmpty(path string) (bool, error) { 58 | f, err := os.Open(path) 59 | if err != nil { 60 | return false, err 61 | } 62 | defer f.Close() 63 | 64 | _, err = f.Readdir(1) 65 | if err == io.EOF { 66 | return true, nil 67 | } 68 | return false, err 69 | } 70 | -------------------------------------------------------------------------------- /bccsp/utils/io_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package utils 18 | 19 | import ( 20 | "os" 21 | "path/filepath" 22 | "testing" 23 | 24 | "github.com/stretchr/testify/assert" 25 | ) 26 | 27 | func TestDirExists(t *testing.T) { 28 | r, err := DirExists("") 29 | assert.False(t, r) 30 | assert.NoError(t, err) 31 | 32 | r, err = DirExists(os.TempDir()) 33 | assert.NoError(t, err) 34 | assert.Equal(t, true, r) 35 | 36 | r, err = DirExists(filepath.Join(os.TempDir(), "7rhf90239vhev90")) 37 | assert.NoError(t, err) 38 | assert.Equal(t, false, r) 39 | } 40 | 41 | func TestDirMissingOrEmpty(t *testing.T) { 42 | r, err := DirMissingOrEmpty("") 43 | assert.NoError(t, err) 44 | assert.True(t, r) 45 | 46 | r, err = DirMissingOrEmpty(filepath.Join(os.TempDir(), "7rhf90239vhev90")) 47 | assert.NoError(t, err) 48 | assert.Equal(t, true, r) 49 | } 50 | 51 | func TestDirEmpty(t *testing.T) { 52 | _, err := DirEmpty("") 53 | assert.Error(t, err) 54 | 55 | path := filepath.Join(os.TempDir(), "7rhf90239vhev90") 56 | defer os.Remove(path) 57 | os.Mkdir(path, os.ModePerm) 58 | 59 | r, err := DirEmpty(path) 60 | assert.NoError(t, err) 61 | assert.Equal(t, true, r) 62 | 63 | r, err = DirEmpty(os.TempDir()) 64 | assert.NoError(t, err) 65 | assert.Equal(t, false, r) 66 | 67 | r, err = DirMissingOrEmpty(os.TempDir()) 68 | assert.NoError(t, err) 69 | assert.Equal(t, false, r) 70 | 71 | r, err = DirMissingOrEmpty(path) 72 | assert.NoError(t, err) 73 | assert.Equal(t, true, r) 74 | } 75 | -------------------------------------------------------------------------------- /bccsp/utils/slice.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package utils 18 | 19 | // Clone clones the passed slice 20 | func Clone(src []byte) []byte { 21 | clone := make([]byte, len(src)) 22 | copy(clone, src) 23 | 24 | return clone 25 | } 26 | -------------------------------------------------------------------------------- /bccsp/utils/slice_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package utils 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/stretchr/testify/assert" 23 | ) 24 | 25 | func TestClone(t *testing.T) { 26 | src := []byte{0, 1, 2, 3, 4} 27 | clone := Clone(src) 28 | assert.Equal(t, src, clone) 29 | } 30 | -------------------------------------------------------------------------------- /bccsp/utils/x509.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package utils 18 | 19 | import ( 20 | "crypto/x509" 21 | ) 22 | 23 | // DERToX509Certificate converts der to x509 24 | func DERToX509Certificate(asn1Data []byte) (*x509.Certificate, error) { 25 | return x509.ParseCertificate(asn1Data) 26 | } 27 | -------------------------------------------------------------------------------- /common/cauthdsl/policy.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package cauthdsl 18 | 19 | import ( 20 | "errors" 21 | "fmt" 22 | 23 | "github.com/traceabilitychain/tacchain/common/policies" 24 | cb "github.com/traceabilitychain/tacchain/protos/common" 25 | 26 | "github.com/golang/protobuf/proto" 27 | "github.com/traceabilitychain/tacchain/msp" 28 | ) 29 | 30 | type provider struct { 31 | deserializer msp.IdentityDeserializer 32 | } 33 | 34 | // NewProviderImpl provides a policy generator for cauthdsl type policies 35 | func NewPolicyProvider(deserializer msp.IdentityDeserializer) policies.Provider { 36 | return &provider{ 37 | deserializer: deserializer, 38 | } 39 | } 40 | 41 | // NewPolicy creates a new policy based on the policy bytes 42 | func (pr *provider) NewPolicy(data []byte) (policies.Policy, proto.Message, error) { 43 | sigPolicy := &cb.SignaturePolicyEnvelope{} 44 | if err := proto.Unmarshal(data, sigPolicy); err != nil { 45 | return nil, nil, fmt.Errorf("Error unmarshaling to SignaturePolicy: %s", err) 46 | } 47 | 48 | if sigPolicy.Version != 0 { 49 | return nil, nil, fmt.Errorf("This evaluator only understands messages of version 0, but version was %d", sigPolicy.Version) 50 | } 51 | 52 | compiled, err := compile(sigPolicy.Rule, sigPolicy.Identities, pr.deserializer) 53 | if err != nil { 54 | return nil, nil, err 55 | } 56 | 57 | return &policy{ 58 | evaluator: compiled, 59 | }, sigPolicy, nil 60 | 61 | } 62 | 63 | type policy struct { 64 | evaluator func([]*cb.SignedData, []bool) bool 65 | } 66 | 67 | // Evaluate takes a set of SignedData and evaluates whether this set of signatures satisfies the policy 68 | func (p *policy) Evaluate(signatureSet []*cb.SignedData) error { 69 | if p == nil { 70 | return fmt.Errorf("No such policy") 71 | } 72 | 73 | ok := p.evaluator(signatureSet, make([]bool, len(signatureSet))) 74 | if !ok { 75 | return errors.New("Failed to authenticate policy") 76 | } 77 | return nil 78 | } 79 | -------------------------------------------------------------------------------- /common/cauthdsl/policy_util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package cauthdsl 18 | 19 | import ( 20 | cb "github.com/traceabilitychain/tacchain/protos/common" 21 | "github.com/traceabilitychain/tacchain/protos/utils" 22 | ) 23 | 24 | // TemplatePolicy creates a headerless configuration item representing a policy for a given key 25 | func TemplatePolicy(key string, sigPolicyEnv *cb.SignaturePolicyEnvelope) *cb.ConfigGroup { 26 | configGroup := cb.NewConfigGroup() 27 | configGroup.Policies[key] = &cb.ConfigPolicy{ 28 | Policy: &cb.Policy{ 29 | Type: int32(cb.Policy_SIGNATURE), 30 | Value: utils.MarshalOrPanic(sigPolicyEnv), 31 | }, 32 | } 33 | return configGroup 34 | } 35 | -------------------------------------------------------------------------------- /common/config/application_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import ( 20 | "testing" 21 | 22 | logging "github.com/op/go-logging" 23 | ) 24 | 25 | func init() { 26 | logging.SetLevel(logging.DEBUG, "") 27 | } 28 | 29 | func TestApplicationInterface(t *testing.T) { 30 | _ = Application((*ApplicationGroup)(nil)) 31 | } 32 | -------------------------------------------------------------------------------- /common/config/application_util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import ( 20 | cb "github.com/traceabilitychain/tacchain/protos/common" 21 | pb "github.com/traceabilitychain/tacchain/protos/peer" 22 | "github.com/traceabilitychain/tacchain/protos/utils" 23 | ) 24 | 25 | func applicationConfigGroup(orgID string, key string, value []byte) *cb.ConfigGroup { 26 | result := cb.NewConfigGroup() 27 | result.Groups[ApplicationGroupKey] = cb.NewConfigGroup() 28 | result.Groups[ApplicationGroupKey].Groups[orgID] = cb.NewConfigGroup() 29 | result.Groups[ApplicationGroupKey].Groups[orgID].Values[key] = &cb.ConfigValue{ 30 | Value: value, 31 | } 32 | return result 33 | } 34 | 35 | // TemplateAnchorPeers creates a headerless config item representing the anchor peers 36 | func TemplateAnchorPeers(orgID string, anchorPeers []*pb.AnchorPeer) *cb.ConfigGroup { 37 | return applicationConfigGroup(orgID, AnchorPeersKey, utils.MarshalOrPanic(&pb.AnchorPeers{AnchorPeers: anchorPeers})) 38 | } 39 | -------------------------------------------------------------------------------- /common/config/applicationorg_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import ( 20 | "testing" 21 | ) 22 | 23 | func TestApplicationOrgInterface(t *testing.T) { 24 | _ = ValueProposer(NewApplicationOrgGroup("id", nil)) 25 | } 26 | -------------------------------------------------------------------------------- /common/config/consortium_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package config 17 | 18 | import ( 19 | "testing" 20 | 21 | "github.com/traceabilitychain/tacchain/common/config/msp" 22 | cb "github.com/traceabilitychain/tacchain/protos/common" 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestConsortiumGroup(t *testing.T) { 27 | 28 | cg := NewConsortiumGroup(msp.NewMSPConfigHandler()) 29 | og, err := cg.NewGroup("testGroup") 30 | assert.NoError(t, err, "NewGroup should not have returned error") 31 | assert.Equal(t, "testGroup", og.(*OrganizationGroup).Name(), 32 | "Unexpected group name returned") 33 | 34 | cc := cg.Allocate() 35 | _, ok := cc.(*ConsortiumConfig) 36 | assert.Equal(t, true, ok, "Allocate should have returned a ConsortiumConfig") 37 | 38 | _, _, err = cg.BeginValueProposals(t, []string{"testGroup"}) 39 | assert.NoError(t, err, "BeginValueProposals should not have returned error") 40 | 41 | err = cg.PreCommit(t) 42 | assert.NoError(t, err, "PreCommit should not have returned error") 43 | cg.CommitProposals(t) 44 | cg.RollbackProposals(t) 45 | 46 | } 47 | 48 | func TestConsortiumConfig(t *testing.T) { 49 | cg := NewConsortiumGroup(msp.NewMSPConfigHandler()) 50 | cc := NewConsortiumConfig(cg) 51 | orgs := cc.Organizations() 52 | assert.Equal(t, 0, len(orgs)) 53 | 54 | policy := cc.ChannelCreationPolicy() 55 | assert.EqualValues(t, cb.Policy_UNKNOWN, policy.Type, "Expected policy type to be UNKNOWN") 56 | 57 | cc.Commit() 58 | assert.Equal(t, cg.ConsortiumConfig, cc, "Error committing ConsortiumConfig") 59 | 60 | og, _ := cg.NewGroup("testGroup") 61 | err := cc.Validate(t, map[string]ValueProposer{ 62 | "testGroup": og, 63 | }) 64 | assert.NoError(t, err, "Validate returned unexpected error") 65 | csg := NewConsortiumsGroup(nil) 66 | err = cc.Validate(t, map[string]ValueProposer{ 67 | "testGroup": csg, 68 | }) 69 | assert.Error(t, err, "Validate should have failed") 70 | 71 | } 72 | -------------------------------------------------------------------------------- /common/config/consortiums_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package config 17 | 18 | import ( 19 | "testing" 20 | 21 | "github.com/stretchr/testify/assert" 22 | ) 23 | 24 | func TestConsortiums(t *testing.T) { 25 | 26 | csg := NewConsortiumsGroup(nil) 27 | cg, err := csg.NewGroup("testCG") 28 | assert.NoError(t, err, "NewGroup shuld not have returned error") 29 | _, ok := cg.(*ConsortiumGroup) 30 | assert.Equal(t, true, ok, "NewGroup should have returned a ConsortiumGroup") 31 | 32 | csc := csg.Allocate() 33 | _, ok = csc.(*ConsortiumsConfig) 34 | assert.Equal(t, true, ok, "Allocate should have returned a ConsortiumsConfig") 35 | 36 | csc.Commit() 37 | assert.Equal(t, csc, csg.ConsortiumsConfig, "Failed to commit ConsortiumsConfig") 38 | 39 | err = csc.Validate(t, map[string]ValueProposer{ 40 | "badGroup": &OrganizationGroup{}, 41 | }) 42 | assert.Error(t, err, "Validate should have returned error for wrong type of ValueProposer") 43 | err = csc.Validate(t, map[string]ValueProposer{ 44 | "testGroup": cg, 45 | }) 46 | assert.NoError(t, err, "Validate should not have returned error") 47 | assert.Equal(t, cg, csc.(*ConsortiumsConfig).Consortiums()["testGroup"], 48 | "Expected consortium groups to be the same") 49 | 50 | } 51 | -------------------------------------------------------------------------------- /common/config/consortiums_util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import ( 20 | cb "github.com/traceabilitychain/tacchain/protos/common" 21 | "github.com/traceabilitychain/tacchain/protos/utils" 22 | ) 23 | 24 | const ( 25 | // ChannelCreationPolicyKey is the key for the ChannelCreationPolicy value 26 | ChannelCreationPolicyKey = "ChannelCreationPolicy" 27 | ) 28 | 29 | // TemplateConsortiumsGroup creates an empty consortiums group 30 | func TemplateConsortiumsGroup() *cb.ConfigGroup { 31 | result := cb.NewConfigGroup() 32 | result.Groups[ConsortiumsGroupKey] = cb.NewConfigGroup() 33 | return result 34 | } 35 | 36 | // TemplateConsortiumChannelCreationPolicy sets the ChannelCreationPolicy for a given consortium 37 | func TemplateConsortiumChannelCreationPolicy(name string, policy *cb.Policy) *cb.ConfigGroup { 38 | result := TemplateConsortiumsGroup() 39 | result.Groups[ConsortiumsGroupKey].Groups[name] = cb.NewConfigGroup() 40 | result.Groups[ConsortiumsGroupKey].Groups[name].Values[ChannelCreationPolicyKey] = &cb.ConfigValue{ 41 | Value: utils.MarshalOrPanic(policy), 42 | } 43 | return result 44 | } 45 | -------------------------------------------------------------------------------- /common/config/orderer_util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import ( 20 | cb "github.com/traceabilitychain/tacchain/protos/common" 21 | ab "github.com/traceabilitychain/tacchain/protos/orderer" 22 | "github.com/traceabilitychain/tacchain/protos/utils" 23 | ) 24 | 25 | func ordererConfigGroup(key string, value []byte) *cb.ConfigGroup { 26 | result := cb.NewConfigGroup() 27 | result.Groups[OrdererGroupKey] = cb.NewConfigGroup() 28 | result.Groups[OrdererGroupKey].Values[key] = &cb.ConfigValue{ 29 | Value: value, 30 | } 31 | return result 32 | } 33 | 34 | // TemplateConsensusType creates a headerless config item representing the consensus type 35 | func TemplateConsensusType(typeValue string) *cb.ConfigGroup { 36 | return ordererConfigGroup(ConsensusTypeKey, utils.MarshalOrPanic(&ab.ConsensusType{Type: typeValue})) 37 | } 38 | 39 | // TemplateBatchSize creates a headerless config item representing the batch size 40 | func TemplateBatchSize(batchSize *ab.BatchSize) *cb.ConfigGroup { 41 | return ordererConfigGroup(BatchSizeKey, utils.MarshalOrPanic(batchSize)) 42 | } 43 | 44 | // TemplateBatchTimeout creates a headerless config item representing the batch timeout 45 | func TemplateBatchTimeout(batchTimeout string) *cb.ConfigGroup { 46 | return ordererConfigGroup(BatchTimeoutKey, utils.MarshalOrPanic(&ab.BatchTimeout{Timeout: batchTimeout})) 47 | } 48 | 49 | // TemplateChannelRestrictions creates a config group with ChannelRestrictions specified 50 | func TemplateChannelRestrictions(maxChannels uint64) *cb.ConfigGroup { 51 | return ordererConfigGroup(ChannelRestrictionsKey, utils.MarshalOrPanic(&ab.ChannelRestrictions{MaxCount: maxChannels})) 52 | } 53 | 54 | // TemplateKafkaBrokers creates a headerless config item representing the kafka brokers 55 | func TemplateKafkaBrokers(brokers []string) *cb.ConfigGroup { 56 | return ordererConfigGroup(KafkaBrokersKey, utils.MarshalOrPanic(&ab.KafkaBrokers{Brokers: brokers})) 57 | } 58 | -------------------------------------------------------------------------------- /common/config/root_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/traceabilitychain/tacchain/common/config/msp" 23 | 24 | logging "github.com/op/go-logging" 25 | "github.com/stretchr/testify/assert" 26 | ) 27 | 28 | func init() { 29 | logging.SetLevel(logging.DEBUG, "") 30 | } 31 | 32 | func TestRoot(t *testing.T) { 33 | r := NewRoot(&msp.MSPConfigHandler{}) 34 | appGroup := &ApplicationGroup{} 35 | ordererGroup := &OrdererGroup{} 36 | consortiumsGroup := &ConsortiumsGroup{} 37 | r.Channel().appConfig = appGroup 38 | r.Channel().ordererConfig = ordererGroup 39 | r.Channel().consortiumsConfig = consortiumsGroup 40 | 41 | assert.Equal(t, appGroup, r.Application(), "Failed to return correct application group") 42 | assert.Equal(t, ordererGroup, r.Orderer(), "Failed to return correct orderer group") 43 | assert.Equal(t, consortiumsGroup, r.Consortiums(), "Failed to return correct consortiums group") 44 | } 45 | 46 | func TestBeginBadRoot(t *testing.T) { 47 | r := NewRoot(&msp.MSPConfigHandler{}) 48 | 49 | _, _, err := r.BeginValueProposals(t, []string{ChannelGroupKey, ChannelGroupKey}) 50 | assert.Error(t, err, "Only one root element allowed") 51 | 52 | _, _, err = r.BeginValueProposals(t, []string{"foo"}) 53 | assert.Error(t, err, "Non %s group not allowed", ChannelGroupKey) 54 | } 55 | 56 | func TestProposeValue(t *testing.T) { 57 | r := NewRoot(msp.NewMSPConfigHandler()) 58 | 59 | vd, _, err := r.BeginValueProposals(t, []string{ChannelGroupKey}) 60 | assert.NoError(t, err) 61 | 62 | _, err = vd.Deserialize("foo", nil) 63 | assert.Error(t, err, "ProposeValue should return error") 64 | } 65 | -------------------------------------------------------------------------------- /common/configtx/test/helper_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package test 18 | 19 | import ( 20 | "os" 21 | "path/filepath" 22 | "testing" 23 | 24 | "github.com/traceabilitychain/tacchain/core/config" 25 | "github.com/traceabilitychain/tacchain/msp" 26 | logging "github.com/op/go-logging" 27 | ) 28 | 29 | func init() { 30 | // Configuration is always specified relative to $GOPATH/github.com/traceabilitychain/tacchain 31 | // This test will fail with the default configuration if executed in the package dir 32 | // We are in common/configtx/test 33 | os.Chdir(filepath.Join("..", "..", "..")) 34 | 35 | logging.SetLevel(logging.DEBUG, "") 36 | } 37 | 38 | func TestMakeGenesisBlock(t *testing.T) { 39 | _, err := MakeGenesisBlock("foo") 40 | if err != nil { 41 | t.Fatalf("Error making genesis block: %s", err) 42 | } 43 | } 44 | 45 | func TestMakeGenesisBlockFromMSPs(t *testing.T) { 46 | 47 | mspDir, err := config.GetDevMspDir() 48 | if err != nil { 49 | t.Fatalf("Error getting DevMspDir: %s", err) 50 | } 51 | 52 | ordererOrgID := "TestOrdererOrg" 53 | appOrgID := "TestAppOrg" 54 | appMSPConf, err := msp.GetLocalMspConfig(mspDir, nil, appOrgID) 55 | if err != nil { 56 | t.Fatalf("Error making genesis block from MSPs: %s", err) 57 | } 58 | ordererMSPConf, err := msp.GetLocalMspConfig(mspDir, nil, ordererOrgID) 59 | if err != nil { 60 | t.Fatalf("Error making genesis block from MSPs: %s", err) 61 | } 62 | _, err = MakeGenesisBlockFromMSPs("foo", appMSPConf, ordererMSPConf, appOrgID, ordererOrgID) 63 | if err != nil { 64 | t.Fatalf("Error making genesis block from MSPs: %s", err) 65 | } 66 | } 67 | 68 | func TestOrdererTemplate(t *testing.T) { 69 | _ = OrdererTemplate() 70 | } 71 | 72 | func TestOrdererOrgTemplate(t *testing.T) { 73 | _ = OrdererOrgTemplate() 74 | } 75 | 76 | func TestApplicationOrgTemplate(t *testing.T) { 77 | _ = ApplicationOrgTemplate() 78 | } 79 | 80 | func TestCompositeTemplate(t *testing.T) { 81 | _ = CompositeTemplate() 82 | } 83 | -------------------------------------------------------------------------------- /common/configtx/tool/configtxgen/metadata/metadata.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 Hitachi America 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package metadata 18 | 19 | import ( 20 | "fmt" 21 | "runtime" 22 | ) 23 | 24 | // Package version 25 | var Version string 26 | 27 | // Program name 28 | const ProgramName = "configtxgen" 29 | 30 | func GetVersionInfo() string { 31 | if Version == "" { 32 | Version = "development build" 33 | } 34 | 35 | return fmt.Sprintf("%s:\n Version: %s\n Go version: %s\n OS/Arch: %s", 36 | ProgramName, Version, runtime.Version(), 37 | fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)) 38 | } 39 | -------------------------------------------------------------------------------- /common/configtx/tool/configtxgen/metadata/metadata_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 Hitachi America 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package metadata_test 18 | 19 | import ( 20 | "fmt" 21 | "runtime" 22 | "testing" 23 | 24 | "github.com/traceabilitychain/tacchain/common/configtx/tool/configtxgen/metadata" 25 | "github.com/stretchr/testify/assert" 26 | ) 27 | 28 | func TestGetVersionInfo(t *testing.T) { 29 | testVersion := "TestVersion" 30 | metadata.Version = testVersion 31 | 32 | expected := fmt.Sprintf("%s:\n Version: %s\n Go version: %s\n OS/Arch: %s", 33 | metadata.ProgramName, testVersion, runtime.Version(), 34 | fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)) 35 | assert.Equal(t, expected, metadata.GetVersionInfo()) 36 | } 37 | -------------------------------------------------------------------------------- /common/configtx/tool/provisional/provisional_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package provisional 18 | 19 | import ( 20 | "bytes" 21 | "testing" 22 | 23 | genesisconfig "github.com/traceabilitychain/tacchain/common/configtx/tool/localconfig" 24 | cb "github.com/traceabilitychain/tacchain/protos/common" 25 | "github.com/stretchr/testify/assert" 26 | ) 27 | 28 | var confSolo *genesisconfig.Profile 29 | var confKafka *genesisconfig.Profile 30 | var testCases []*genesisconfig.Profile 31 | 32 | func init() { 33 | confSolo = genesisconfig.Load(genesisconfig.SampleSingleMSPSoloProfile) 34 | confKafka = genesisconfig.Load("SampleInsecureKafka") 35 | testCases = []*genesisconfig.Profile{confSolo, confKafka} 36 | } 37 | 38 | func TestGenesisBlockHeader(t *testing.T) { 39 | expectedHeaderNumber := uint64(0) 40 | 41 | for _, tc := range testCases { 42 | genesisBlock := New(tc).GenesisBlock() 43 | if genesisBlock.Header.Number != expectedHeaderNumber { 44 | t.Fatalf("Case %s: Expected header number %d, got %d", tc.Orderer.OrdererType, expectedHeaderNumber, genesisBlock.Header.Number) 45 | } 46 | if !bytes.Equal(genesisBlock.Header.PreviousHash, nil) { 47 | t.Fatalf("Case %s: Expected header previousHash to be nil, got %x", tc.Orderer.OrdererType, genesisBlock.Header.PreviousHash) 48 | } 49 | } 50 | } 51 | 52 | func TestGenesisMetadata(t *testing.T) { 53 | for _, tc := range testCases { 54 | genesisBlock := New(tc).GenesisBlock() 55 | if genesisBlock.Metadata == nil { 56 | t.Fatalf("Expected non-nil metadata") 57 | } 58 | 59 | if genesisBlock.Metadata.Metadata[cb.BlockMetadataIndex_LAST_CONFIG] == nil { 60 | t.Fatalf("Should have last config set") 61 | } 62 | } 63 | } 64 | 65 | func TestGenesisBlockForChannelHeader(t *testing.T) { 66 | expectedHeaderNumber := uint64(0) 67 | 68 | for _, tc := range testCases { 69 | genesisBlock := New(tc).GenesisBlockForChannel("mychannel") 70 | assert.Equal(t, expectedHeaderNumber, genesisBlock.Header.Number, "Case %s: Header number should be equal", tc.Orderer.OrdererType) 71 | assert.Nil(t, genesisBlock.Header.PreviousHash, "Case %s: Header previousHash to be nil", tc.Orderer.OrdererType) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /common/crypto/random.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package crypto 18 | 19 | import "crypto/rand" 20 | 21 | const ( 22 | // NonceSize is the default NonceSize 23 | NonceSize = 24 24 | ) 25 | 26 | // GetRandomBytes returns len random looking bytes 27 | func GetRandomBytes(len int) ([]byte, error) { 28 | key := make([]byte, len) 29 | 30 | // TODO: rand could fill less bytes then len 31 | _, err := rand.Read(key) 32 | if err != nil { 33 | return nil, err 34 | } 35 | 36 | return key, nil 37 | } 38 | 39 | // GetRandomNonce returns a random byte array of length NonceSize 40 | func GetRandomNonce() ([]byte, error) { 41 | return GetRandomBytes(NonceSize) 42 | } 43 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | 24 | *~ 25 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/.gitignore: -------------------------------------------------------------------------------- 1 | bench_inv 2 | bench_ecdh 3 | bench_sign 4 | bench_verify 5 | bench_schnorr_verify 6 | bench_recover 7 | bench_internal 8 | tests 9 | exhaustive_tests 10 | gen_context 11 | *.exe 12 | *.so 13 | *.a 14 | !.gitignore 15 | 16 | Makefile 17 | configure 18 | .libs/ 19 | Makefile.in 20 | aclocal.m4 21 | autom4te.cache/ 22 | config.log 23 | config.status 24 | *.tar.gz 25 | *.la 26 | libtool 27 | .deps/ 28 | .dirstamp 29 | *.lo 30 | *.o 31 | *~ 32 | src/libsecp256k1-config.h 33 | src/libsecp256k1-config.h.in 34 | src/ecmult_static_context.h 35 | build-aux/config.guess 36 | build-aux/config.sub 37 | build-aux/depcomp 38 | build-aux/install-sh 39 | build-aux/ltmain.sh 40 | build-aux/m4/libtool.m4 41 | build-aux/m4/lt~obsolete.m4 42 | build-aux/m4/ltoptions.m4 43 | build-aux/m4/ltsugar.m4 44 | build-aux/m4/ltversion.m4 45 | build-aux/missing 46 | build-aux/compile 47 | build-aux/test-driver 48 | src/stamp-h1 49 | libsecp256k1.pc 50 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | sudo: false 3 | addons: 4 | apt: 5 | packages: libgmp-dev 6 | compiler: 7 | - clang 8 | - gcc 9 | cache: 10 | directories: 11 | - src/java/guava/ 12 | env: 13 | global: 14 | - FIELD=auto BIGNUM=auto SCALAR=auto ENDOMORPHISM=no STATICPRECOMPUTATION=yes ASM=no BUILD=check EXTRAFLAGS= HOST= ECDH=no RECOVERY=no EXPERIMENTAL=no 15 | - GUAVA_URL=https://search.maven.org/remotecontent?filepath=com/google/guava/guava/18.0/guava-18.0.jar GUAVA_JAR=src/java/guava/guava-18.0.jar 16 | matrix: 17 | - SCALAR=32bit RECOVERY=yes 18 | - SCALAR=32bit FIELD=32bit ECDH=yes EXPERIMENTAL=yes 19 | - SCALAR=64bit 20 | - FIELD=64bit RECOVERY=yes 21 | - FIELD=64bit ENDOMORPHISM=yes 22 | - FIELD=64bit ENDOMORPHISM=yes ECDH=yes EXPERIMENTAL=yes 23 | - FIELD=64bit ASM=x86_64 24 | - FIELD=64bit ENDOMORPHISM=yes ASM=x86_64 25 | - FIELD=32bit ENDOMORPHISM=yes 26 | - BIGNUM=no 27 | - BIGNUM=no ENDOMORPHISM=yes RECOVERY=yes EXPERIMENTAL=yes 28 | - BIGNUM=no STATICPRECOMPUTATION=no 29 | - BUILD=distcheck 30 | - EXTRAFLAGS=CPPFLAGS=-DDETERMINISTIC 31 | - EXTRAFLAGS=CFLAGS=-O0 32 | - BUILD=check-java ECDH=yes EXPERIMENTAL=yes 33 | matrix: 34 | fast_finish: true 35 | include: 36 | - compiler: clang 37 | env: HOST=i686-linux-gnu ENDOMORPHISM=yes 38 | addons: 39 | apt: 40 | packages: 41 | - gcc-multilib 42 | - libgmp-dev:i386 43 | - compiler: clang 44 | env: HOST=i686-linux-gnu 45 | addons: 46 | apt: 47 | packages: 48 | - gcc-multilib 49 | - compiler: gcc 50 | env: HOST=i686-linux-gnu ENDOMORPHISM=yes 51 | addons: 52 | apt: 53 | packages: 54 | - gcc-multilib 55 | - compiler: gcc 56 | env: HOST=i686-linux-gnu 57 | addons: 58 | apt: 59 | packages: 60 | - gcc-multilib 61 | - libgmp-dev:i386 62 | before_install: mkdir -p `dirname $GUAVA_JAR` 63 | install: if [ ! -f $GUAVA_JAR ]; then wget $GUAVA_URL -O $GUAVA_JAR; fi 64 | before_script: ./autogen.sh 65 | script: 66 | - if [ -n "$HOST" ]; then export USE_HOST="--host=$HOST"; fi 67 | - if [ "x$HOST" = "xi686-linux-gnu" ]; then export CC="$CC -m32"; fi 68 | - ./configure --enable-experimental=$EXPERIMENTAL --enable-endomorphism=$ENDOMORPHISM --with-field=$FIELD --with-bignum=$BIGNUM --with-scalar=$SCALAR --enable-ecmult-static-precomputation=$STATICPRECOMPUTATION --enable-module-ecdh=$ECDH --enable-module-recovery=$RECOVERY $EXTRAFLAGS $USE_HOST && make -j2 $BUILD 69 | os: linux 70 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/COPYING: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Pieter Wuille 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/TODO: -------------------------------------------------------------------------------- 1 | * Unit tests for fieldelem/groupelem, including ones intended to 2 | trigger fieldelem's boundary cases. 3 | * Complete constant-time operations for signing/keygen 4 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/autogen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | autoreconf -if --warnings=all 4 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/build-aux/m4/bitcoin_secp.m4: -------------------------------------------------------------------------------- 1 | dnl libsecp25k1 helper checks 2 | AC_DEFUN([SECP_INT128_CHECK],[ 3 | has_int128=$ac_cv_type___int128 4 | ]) 5 | 6 | dnl escape "$0x" below using the m4 quadrigaph @S|@, and escape it again with a \ for the shell. 7 | AC_DEFUN([SECP_64BIT_ASM_CHECK],[ 8 | AC_MSG_CHECKING(for x86_64 assembly availability) 9 | AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ 10 | #include ]],[[ 11 | uint64_t a = 11, tmp; 12 | __asm__ __volatile__("movq \@S|@0x100000000,%1; mulq %%rsi" : "+a"(a) : "S"(tmp) : "cc", "%rdx"); 13 | ]])],[has_64bit_asm=yes],[has_64bit_asm=no]) 14 | AC_MSG_RESULT([$has_64bit_asm]) 15 | ]) 16 | 17 | dnl 18 | AC_DEFUN([SECP_OPENSSL_CHECK],[ 19 | has_libcrypto=no 20 | m4_ifdef([PKG_CHECK_MODULES],[ 21 | PKG_CHECK_MODULES([CRYPTO], [libcrypto], [has_libcrypto=yes],[has_libcrypto=no]) 22 | if test x"$has_libcrypto" = x"yes"; then 23 | TEMP_LIBS="$LIBS" 24 | LIBS="$LIBS $CRYPTO_LIBS" 25 | AC_CHECK_LIB(crypto, main,[AC_DEFINE(HAVE_LIBCRYPTO,1,[Define this symbol if libcrypto is installed])],[has_libcrypto=no]) 26 | LIBS="$TEMP_LIBS" 27 | fi 28 | ]) 29 | if test x$has_libcrypto = xno; then 30 | AC_CHECK_HEADER(openssl/crypto.h,[ 31 | AC_CHECK_LIB(crypto, main,[ 32 | has_libcrypto=yes 33 | CRYPTO_LIBS=-lcrypto 34 | AC_DEFINE(HAVE_LIBCRYPTO,1,[Define this symbol if libcrypto is installed]) 35 | ]) 36 | ]) 37 | LIBS= 38 | fi 39 | if test x"$has_libcrypto" = x"yes" && test x"$has_openssl_ec" = x; then 40 | AC_MSG_CHECKING(for EC functions in libcrypto) 41 | AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ 42 | #include 43 | #include 44 | #include ]],[[ 45 | EC_KEY *eckey = EC_KEY_new_by_curve_name(NID_secp256k1); 46 | ECDSA_sign(0, NULL, 0, NULL, NULL, eckey); 47 | ECDSA_verify(0, NULL, 0, NULL, 0, eckey); 48 | EC_KEY_free(eckey); 49 | ECDSA_SIG *sig_openssl; 50 | sig_openssl = ECDSA_SIG_new(); 51 | (void)sig_openssl->r; 52 | ECDSA_SIG_free(sig_openssl); 53 | ]])],[has_openssl_ec=yes],[has_openssl_ec=no]) 54 | AC_MSG_RESULT([$has_openssl_ec]) 55 | fi 56 | ]) 57 | 58 | dnl 59 | AC_DEFUN([SECP_GMP_CHECK],[ 60 | if test x"$has_gmp" != x"yes"; then 61 | CPPFLAGS_TEMP="$CPPFLAGS" 62 | CPPFLAGS="$GMP_CPPFLAGS $CPPFLAGS" 63 | LIBS_TEMP="$LIBS" 64 | LIBS="$GMP_LIBS $LIBS" 65 | AC_CHECK_HEADER(gmp.h,[AC_CHECK_LIB(gmp, __gmpz_init,[has_gmp=yes; GMP_LIBS="$GMP_LIBS -lgmp"; AC_DEFINE(HAVE_LIBGMP,1,[Define this symbol if libgmp is installed])])]) 66 | CPPFLAGS="$CPPFLAGS_TEMP" 67 | LIBS="$LIBS_TEMP" 68 | fi 69 | ]) 70 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/include/secp256k1_ecdh.h: -------------------------------------------------------------------------------- 1 | #ifndef _SECP256K1_ECDH_ 2 | # define _SECP256K1_ECDH_ 3 | 4 | # include "secp256k1.h" 5 | 6 | # ifdef __cplusplus 7 | extern "C" { 8 | # endif 9 | 10 | /** Compute an EC Diffie-Hellman secret in constant time 11 | * Returns: 1: exponentiation was successful 12 | * 0: scalar was invalid (zero or overflow) 13 | * Args: ctx: pointer to a context object (cannot be NULL) 14 | * Out: result: a 32-byte array which will be populated by an ECDH 15 | * secret computed from the point and scalar 16 | * In: pubkey: a pointer to a secp256k1_pubkey containing an 17 | * initialized public key 18 | * privkey: a 32-byte scalar with which to multiply the point 19 | */ 20 | SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdh( 21 | const secp256k1_context* ctx, 22 | unsigned char *result, 23 | const secp256k1_pubkey *pubkey, 24 | const unsigned char *privkey 25 | ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); 26 | 27 | # ifdef __cplusplus 28 | } 29 | # endif 30 | 31 | #endif 32 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/libsecp256k1.pc.in: -------------------------------------------------------------------------------- 1 | prefix=@prefix@ 2 | exec_prefix=@exec_prefix@ 3 | libdir=@libdir@ 4 | includedir=@includedir@ 5 | 6 | Name: libsecp256k1 7 | Description: Optimized C library for EC operations on curve secp256k1 8 | URL: https://github.com/bitcoin-core/secp256k1 9 | Version: @PACKAGE_VERSION@ 10 | Cflags: -I${includedir} 11 | Libs.private: @SECP_LIBS@ 12 | Libs: -L${libdir} -lsecp256k1 13 | 14 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/obj/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TraceabilityChain/TAC/3da98e9661457977f5b992e7a5a12e4d26133ca0/common/crypto/secp256k1/libsecp256k1/obj/.gitignore -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/basic-config.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_BASIC_CONFIG_ 8 | #define _SECP256K1_BASIC_CONFIG_ 9 | 10 | #ifdef USE_BASIC_CONFIG 11 | 12 | #undef USE_ASM_X86_64 13 | #undef USE_ENDOMORPHISM 14 | #undef USE_FIELD_10X26 15 | #undef USE_FIELD_5X52 16 | #undef USE_FIELD_INV_BUILTIN 17 | #undef USE_FIELD_INV_NUM 18 | #undef USE_NUM_GMP 19 | #undef USE_NUM_NONE 20 | #undef USE_SCALAR_4X64 21 | #undef USE_SCALAR_8X32 22 | #undef USE_SCALAR_INV_BUILTIN 23 | #undef USE_SCALAR_INV_NUM 24 | 25 | #define USE_NUM_NONE 1 26 | #define USE_FIELD_INV_BUILTIN 1 27 | #define USE_SCALAR_INV_BUILTIN 1 28 | #define USE_FIELD_10X26 1 29 | #define USE_SCALAR_8X32 1 30 | 31 | #endif // USE_BASIC_CONFIG 32 | #endif // _SECP256K1_BASIC_CONFIG_ 33 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/bench.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_BENCH_H_ 8 | #define _SECP256K1_BENCH_H_ 9 | 10 | #include 11 | #include 12 | #include "sys/time.h" 13 | 14 | static double gettimedouble(void) { 15 | struct timeval tv; 16 | gettimeofday(&tv, NULL); 17 | return tv.tv_usec * 0.000001 + tv.tv_sec; 18 | } 19 | 20 | void print_number(double x) { 21 | double y = x; 22 | int c = 0; 23 | if (y < 0.0) { 24 | y = -y; 25 | } 26 | while (y < 100.0) { 27 | y *= 10.0; 28 | c++; 29 | } 30 | printf("%.*f", c, x); 31 | } 32 | 33 | void run_benchmark(char *name, void (*benchmark)(void*), void (*setup)(void*), void (*teardown)(void*), void* data, int count, int iter) { 34 | int i; 35 | double min = HUGE_VAL; 36 | double sum = 0.0; 37 | double max = 0.0; 38 | for (i = 0; i < count; i++) { 39 | double begin, total; 40 | if (setup != NULL) { 41 | setup(data); 42 | } 43 | begin = gettimedouble(); 44 | benchmark(data); 45 | total = gettimedouble() - begin; 46 | if (teardown != NULL) { 47 | teardown(data); 48 | } 49 | if (total < min) { 50 | min = total; 51 | } 52 | if (total > max) { 53 | max = total; 54 | } 55 | sum += total; 56 | } 57 | printf("%s: min ", name); 58 | print_number(min * 1000000.0 / iter); 59 | printf("us / avg "); 60 | print_number((sum / count) * 1000000.0 / iter); 61 | printf("us / max "); 62 | print_number(max * 1000000.0 / iter); 63 | printf("us\n"); 64 | } 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/bench_ecdh.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Pieter Wuille, Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | 9 | #include "include/secp256k1.h" 10 | #include "include/secp256k1_ecdh.h" 11 | #include "util.h" 12 | #include "bench.h" 13 | 14 | typedef struct { 15 | secp256k1_context *ctx; 16 | secp256k1_pubkey point; 17 | unsigned char scalar[32]; 18 | } bench_ecdh_t; 19 | 20 | static void bench_ecdh_setup(void* arg) { 21 | int i; 22 | bench_ecdh_t *data = (bench_ecdh_t*)arg; 23 | const unsigned char point[] = { 24 | 0x03, 25 | 0x54, 0x94, 0xc1, 0x5d, 0x32, 0x09, 0x97, 0x06, 26 | 0xc2, 0x39, 0x5f, 0x94, 0x34, 0x87, 0x45, 0xfd, 27 | 0x75, 0x7c, 0xe3, 0x0e, 0x4e, 0x8c, 0x90, 0xfb, 28 | 0xa2, 0xba, 0xd1, 0x84, 0xf8, 0x83, 0xc6, 0x9f 29 | }; 30 | 31 | /* create a context with no capabilities */ 32 | data->ctx = secp256k1_context_create(SECP256K1_FLAGS_TYPE_CONTEXT); 33 | for (i = 0; i < 32; i++) { 34 | data->scalar[i] = i + 1; 35 | } 36 | CHECK(secp256k1_ec_pubkey_parse(data->ctx, &data->point, point, sizeof(point)) == 1); 37 | } 38 | 39 | static void bench_ecdh(void* arg) { 40 | int i; 41 | unsigned char res[32]; 42 | bench_ecdh_t *data = (bench_ecdh_t*)arg; 43 | 44 | for (i = 0; i < 20000; i++) { 45 | CHECK(secp256k1_ecdh(data->ctx, res, &data->point, data->scalar) == 1); 46 | } 47 | } 48 | 49 | int main(void) { 50 | bench_ecdh_t data; 51 | 52 | run_benchmark("ecdh", bench_ecdh, bench_ecdh_setup, NULL, &data, 10, 20000); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/bench_recover.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014-2015 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include "include/secp256k1.h" 8 | #include "include/secp256k1_recovery.h" 9 | #include "util.h" 10 | #include "bench.h" 11 | 12 | typedef struct { 13 | secp256k1_context *ctx; 14 | unsigned char msg[32]; 15 | unsigned char sig[64]; 16 | } bench_recover_t; 17 | 18 | void bench_recover(void* arg) { 19 | int i; 20 | bench_recover_t *data = (bench_recover_t*)arg; 21 | secp256k1_pubkey pubkey; 22 | unsigned char pubkeyc[33]; 23 | 24 | for (i = 0; i < 20000; i++) { 25 | int j; 26 | size_t pubkeylen = 33; 27 | secp256k1_ecdsa_recoverable_signature sig; 28 | CHECK(secp256k1_ecdsa_recoverable_signature_parse_compact(data->ctx, &sig, data->sig, i % 2)); 29 | CHECK(secp256k1_ecdsa_recover(data->ctx, &pubkey, &sig, data->msg)); 30 | CHECK(secp256k1_ec_pubkey_serialize(data->ctx, pubkeyc, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED)); 31 | for (j = 0; j < 32; j++) { 32 | data->sig[j + 32] = data->msg[j]; /* Move former message to S. */ 33 | data->msg[j] = data->sig[j]; /* Move former R to message. */ 34 | data->sig[j] = pubkeyc[j + 1]; /* Move recovered pubkey X coordinate to R (which must be a valid X coordinate). */ 35 | } 36 | } 37 | } 38 | 39 | void bench_recover_setup(void* arg) { 40 | int i; 41 | bench_recover_t *data = (bench_recover_t*)arg; 42 | 43 | for (i = 0; i < 32; i++) { 44 | data->msg[i] = 1 + i; 45 | } 46 | for (i = 0; i < 64; i++) { 47 | data->sig[i] = 65 + i; 48 | } 49 | } 50 | 51 | int main(void) { 52 | bench_recover_t data; 53 | 54 | data.ctx = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); 55 | 56 | run_benchmark("ecdsa_recover", bench_recover, bench_recover_setup, NULL, &data, 10, 20000); 57 | 58 | secp256k1_context_destroy(data.ctx); 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/bench_sign.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include "include/secp256k1.h" 8 | #include "util.h" 9 | #include "bench.h" 10 | 11 | typedef struct { 12 | secp256k1_context* ctx; 13 | unsigned char msg[32]; 14 | unsigned char key[32]; 15 | } bench_sign_t; 16 | 17 | static void bench_sign_setup(void* arg) { 18 | int i; 19 | bench_sign_t *data = (bench_sign_t*)arg; 20 | 21 | for (i = 0; i < 32; i++) { 22 | data->msg[i] = i + 1; 23 | } 24 | for (i = 0; i < 32; i++) { 25 | data->key[i] = i + 65; 26 | } 27 | } 28 | 29 | static void bench_sign(void* arg) { 30 | int i; 31 | bench_sign_t *data = (bench_sign_t*)arg; 32 | 33 | unsigned char sig[74]; 34 | for (i = 0; i < 20000; i++) { 35 | size_t siglen = 74; 36 | int j; 37 | secp256k1_ecdsa_signature signature; 38 | CHECK(secp256k1_ecdsa_sign(data->ctx, &signature, data->msg, data->key, NULL, NULL)); 39 | CHECK(secp256k1_ecdsa_signature_serialize_der(data->ctx, sig, &siglen, &signature)); 40 | for (j = 0; j < 32; j++) { 41 | data->msg[j] = sig[j]; 42 | data->key[j] = sig[j + 32]; 43 | } 44 | } 45 | } 46 | 47 | int main(void) { 48 | bench_sign_t data; 49 | 50 | data.ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); 51 | 52 | run_benchmark("ecdsa_sign", bench_sign, bench_sign_setup, NULL, &data, 10, 20000); 53 | 54 | secp256k1_context_destroy(data.ctx); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/ecdsa.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECDSA_ 8 | #define _SECP256K1_ECDSA_ 9 | 10 | #include 11 | 12 | #include "scalar.h" 13 | #include "group.h" 14 | #include "ecmult.h" 15 | 16 | static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *r, secp256k1_scalar *s, const unsigned char *sig, size_t size); 17 | static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const secp256k1_scalar *r, const secp256k1_scalar *s); 18 | static int secp256k1_ecdsa_sig_verify(const secp256k1_ecmult_context *ctx, const secp256k1_scalar* r, const secp256k1_scalar* s, const secp256k1_ge *pubkey, const secp256k1_scalar *message); 19 | static int secp256k1_ecdsa_sig_sign(const secp256k1_ecmult_gen_context *ctx, secp256k1_scalar* r, secp256k1_scalar* s, const secp256k1_scalar *seckey, const secp256k1_scalar *message, const secp256k1_scalar *nonce, int *recid); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/eckey.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECKEY_ 8 | #define _SECP256K1_ECKEY_ 9 | 10 | #include 11 | 12 | #include "group.h" 13 | #include "scalar.h" 14 | #include "ecmult.h" 15 | #include "ecmult_gen.h" 16 | 17 | static int secp256k1_eckey_pubkey_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size); 18 | static int secp256k1_eckey_pubkey_serialize(secp256k1_ge *elem, unsigned char *pub, size_t *size, int compressed); 19 | 20 | static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar *key, const secp256k1_scalar *tweak); 21 | static int secp256k1_eckey_pubkey_tweak_add(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); 22 | static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar *key, const secp256k1_scalar *tweak); 23 | static int secp256k1_eckey_pubkey_tweak_mul(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/ecmult.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECMULT_ 8 | #define _SECP256K1_ECMULT_ 9 | 10 | #include "num.h" 11 | #include "group.h" 12 | 13 | typedef struct { 14 | /* For accelerating the computation of a*P + b*G: */ 15 | secp256k1_ge_storage (*pre_g)[]; /* odd multiples of the generator */ 16 | #ifdef USE_ENDOMORPHISM 17 | secp256k1_ge_storage (*pre_g_128)[]; /* odd multiples of 2^128*generator */ 18 | #endif 19 | } secp256k1_ecmult_context; 20 | 21 | static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx); 22 | static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb); 23 | static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, 24 | const secp256k1_ecmult_context *src, const secp256k1_callback *cb); 25 | static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx); 26 | static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx); 27 | 28 | /** Double multiply: R = na*A + ng*G */ 29 | static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng); 30 | 31 | #endif 32 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/ecmult_const.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECMULT_CONST_ 8 | #define _SECP256K1_ECMULT_CONST_ 9 | 10 | #include "scalar.h" 11 | #include "group.h" 12 | 13 | static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q); 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/ecmult_gen.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECMULT_GEN_ 8 | #define _SECP256K1_ECMULT_GEN_ 9 | 10 | #include "scalar.h" 11 | #include "group.h" 12 | 13 | typedef struct { 14 | /* For accelerating the computation of a*G: 15 | * To harden against timing attacks, use the following mechanism: 16 | * * Break up the multiplicand into groups of 4 bits, called n_0, n_1, n_2, ..., n_63. 17 | * * Compute sum(n_i * 16^i * G + U_i, i=0..63), where: 18 | * * U_i = U * 2^i (for i=0..62) 19 | * * U_i = U * (1-2^63) (for i=63) 20 | * where U is a point with no known corresponding scalar. Note that sum(U_i, i=0..63) = 0. 21 | * For each i, and each of the 16 possible values of n_i, (n_i * 16^i * G + U_i) is 22 | * precomputed (call it prec(i, n_i)). The formula now becomes sum(prec(i, n_i), i=0..63). 23 | * None of the resulting prec group elements have a known scalar, and neither do any of 24 | * the intermediate sums while computing a*G. 25 | */ 26 | secp256k1_ge_storage (*prec)[64][16]; /* prec[j][i] = 16^j * i * G + U_i */ 27 | secp256k1_scalar blind; 28 | secp256k1_gej initial; 29 | } secp256k1_ecmult_gen_context; 30 | 31 | static void secp256k1_ecmult_gen_context_init(secp256k1_ecmult_gen_context* ctx); 32 | static void secp256k1_ecmult_gen_context_build(secp256k1_ecmult_gen_context* ctx, const secp256k1_callback* cb); 33 | static void secp256k1_ecmult_gen_context_clone(secp256k1_ecmult_gen_context *dst, 34 | const secp256k1_ecmult_gen_context* src, const secp256k1_callback* cb); 35 | static void secp256k1_ecmult_gen_context_clear(secp256k1_ecmult_gen_context* ctx); 36 | static int secp256k1_ecmult_gen_context_is_built(const secp256k1_ecmult_gen_context* ctx); 37 | 38 | /** Multiply with the generator: R = a*G */ 39 | static void secp256k1_ecmult_gen(const secp256k1_ecmult_gen_context* ctx, secp256k1_gej *r, const secp256k1_scalar *a); 40 | 41 | static void secp256k1_ecmult_gen_blind(secp256k1_ecmult_gen_context *ctx, const unsigned char *seed32); 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/field_10x26.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_FIELD_REPR_ 8 | #define _SECP256K1_FIELD_REPR_ 9 | 10 | #include 11 | 12 | typedef struct { 13 | /* X = sum(i=0..9, elem[i]*2^26) mod n */ 14 | uint32_t n[10]; 15 | #ifdef VERIFY 16 | int magnitude; 17 | int normalized; 18 | #endif 19 | } secp256k1_fe; 20 | 21 | /* Unpacks a constant into a overlapping multi-limbed FE element. */ 22 | #define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \ 23 | (d0) & 0x3FFFFFFUL, \ 24 | (((uint32_t)d0) >> 26) | (((uint32_t)(d1) & 0xFFFFFUL) << 6), \ 25 | (((uint32_t)d1) >> 20) | (((uint32_t)(d2) & 0x3FFFUL) << 12), \ 26 | (((uint32_t)d2) >> 14) | (((uint32_t)(d3) & 0xFFUL) << 18), \ 27 | (((uint32_t)d3) >> 8) | (((uint32_t)(d4) & 0x3UL) << 24), \ 28 | (((uint32_t)d4) >> 2) & 0x3FFFFFFUL, \ 29 | (((uint32_t)d4) >> 28) | (((uint32_t)(d5) & 0x3FFFFFUL) << 4), \ 30 | (((uint32_t)d5) >> 22) | (((uint32_t)(d6) & 0xFFFFUL) << 10), \ 31 | (((uint32_t)d6) >> 16) | (((uint32_t)(d7) & 0x3FFUL) << 16), \ 32 | (((uint32_t)d7) >> 10) \ 33 | } 34 | 35 | #ifdef VERIFY 36 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)), 1, 1} 37 | #else 38 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))} 39 | #endif 40 | 41 | typedef struct { 42 | uint32_t n[8]; 43 | } secp256k1_fe_storage; 44 | 45 | #define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ (d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }} 46 | #define SECP256K1_FE_STORAGE_CONST_GET(d) d.n[7], d.n[6], d.n[5], d.n[4],d.n[3], d.n[2], d.n[1], d.n[0] 47 | #endif 48 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/field_5x52.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_FIELD_REPR_ 8 | #define _SECP256K1_FIELD_REPR_ 9 | 10 | #include 11 | 12 | typedef struct { 13 | /* X = sum(i=0..4, elem[i]*2^52) mod n */ 14 | uint64_t n[5]; 15 | #ifdef VERIFY 16 | int magnitude; 17 | int normalized; 18 | #endif 19 | } secp256k1_fe; 20 | 21 | /* Unpacks a constant into a overlapping multi-limbed FE element. */ 22 | #define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \ 23 | (d0) | (((uint64_t)(d1) & 0xFFFFFUL) << 32), \ 24 | ((uint64_t)(d1) >> 20) | (((uint64_t)(d2)) << 12) | (((uint64_t)(d3) & 0xFFUL) << 44), \ 25 | ((uint64_t)(d3) >> 8) | (((uint64_t)(d4) & 0xFFFFFFFUL) << 24), \ 26 | ((uint64_t)(d4) >> 28) | (((uint64_t)(d5)) << 4) | (((uint64_t)(d6) & 0xFFFFUL) << 36), \ 27 | ((uint64_t)(d6) >> 16) | (((uint64_t)(d7)) << 16) \ 28 | } 29 | 30 | #ifdef VERIFY 31 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)), 1, 1} 32 | #else 33 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))} 34 | #endif 35 | 36 | typedef struct { 37 | uint64_t n[4]; 38 | } secp256k1_fe_storage; 39 | 40 | #define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ \ 41 | (d0) | (((uint64_t)(d1)) << 32), \ 42 | (d2) | (((uint64_t)(d3)) << 32), \ 43 | (d4) | (((uint64_t)(d5)) << 32), \ 44 | (d6) | (((uint64_t)(d7)) << 32) \ 45 | }} 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/gen_context.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014, 2015 Thomas Daede, Cory Fields * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #define USE_BASIC_CONFIG 1 8 | 9 | #include "basic-config.h" 10 | #include "include/secp256k1.h" 11 | #include "field_impl.h" 12 | #include "scalar_impl.h" 13 | #include "group_impl.h" 14 | #include "ecmult_gen_impl.h" 15 | 16 | static void default_error_callback_fn(const char* str, void* data) { 17 | (void)data; 18 | fprintf(stderr, "[libsecp256k1] internal consistency check failed: %s\n", str); 19 | abort(); 20 | } 21 | 22 | static const secp256k1_callback default_error_callback = { 23 | default_error_callback_fn, 24 | NULL 25 | }; 26 | 27 | int main(int argc, char **argv) { 28 | secp256k1_ecmult_gen_context ctx; 29 | int inner; 30 | int outer; 31 | FILE* fp; 32 | 33 | (void)argc; 34 | (void)argv; 35 | 36 | fp = fopen("src/ecmult_static_context.h","w"); 37 | if (fp == NULL) { 38 | fprintf(stderr, "Could not open src/ecmult_static_context.h for writing!\n"); 39 | return -1; 40 | } 41 | 42 | fprintf(fp, "#ifndef _SECP256K1_ECMULT_STATIC_CONTEXT_\n"); 43 | fprintf(fp, "#define _SECP256K1_ECMULT_STATIC_CONTEXT_\n"); 44 | fprintf(fp, "#include \"group.h\"\n"); 45 | fprintf(fp, "#define SC SECP256K1_GE_STORAGE_CONST\n"); 46 | fprintf(fp, "static const secp256k1_ge_storage secp256k1_ecmult_static_context[64][16] = {\n"); 47 | 48 | secp256k1_ecmult_gen_context_init(&ctx); 49 | secp256k1_ecmult_gen_context_build(&ctx, &default_error_callback); 50 | for(outer = 0; outer != 64; outer++) { 51 | fprintf(fp,"{\n"); 52 | for(inner = 0; inner != 16; inner++) { 53 | fprintf(fp," SC(%uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu)", SECP256K1_GE_STORAGE_CONST_GET((*ctx.prec)[outer][inner])); 54 | if (inner != 15) { 55 | fprintf(fp,",\n"); 56 | } else { 57 | fprintf(fp,"\n"); 58 | } 59 | } 60 | if (outer != 63) { 61 | fprintf(fp,"},\n"); 62 | } else { 63 | fprintf(fp,"}\n"); 64 | } 65 | } 66 | fprintf(fp,"};\n"); 67 | secp256k1_ecmult_gen_context_clear(&ctx); 68 | 69 | fprintf(fp, "#undef SC\n"); 70 | fprintf(fp, "#endif\n"); 71 | fclose(fp); 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/hash.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_HASH_ 8 | #define _SECP256K1_HASH_ 9 | 10 | #include 11 | #include 12 | 13 | typedef struct { 14 | uint32_t s[8]; 15 | uint32_t buf[16]; /* In big endian */ 16 | size_t bytes; 17 | } secp256k1_sha256_t; 18 | 19 | static void secp256k1_sha256_initialize(secp256k1_sha256_t *hash); 20 | static void secp256k1_sha256_write(secp256k1_sha256_t *hash, const unsigned char *data, size_t size); 21 | static void secp256k1_sha256_finalize(secp256k1_sha256_t *hash, unsigned char *out32); 22 | 23 | typedef struct { 24 | secp256k1_sha256_t inner, outer; 25 | } secp256k1_hmac_sha256_t; 26 | 27 | static void secp256k1_hmac_sha256_initialize(secp256k1_hmac_sha256_t *hash, const unsigned char *key, size_t size); 28 | static void secp256k1_hmac_sha256_write(secp256k1_hmac_sha256_t *hash, const unsigned char *data, size_t size); 29 | static void secp256k1_hmac_sha256_finalize(secp256k1_hmac_sha256_t *hash, unsigned char *out32); 30 | 31 | typedef struct { 32 | unsigned char v[32]; 33 | unsigned char k[32]; 34 | int retry; 35 | } secp256k1_rfc6979_hmac_sha256_t; 36 | 37 | static void secp256k1_rfc6979_hmac_sha256_initialize(secp256k1_rfc6979_hmac_sha256_t *rng, const unsigned char *key, size_t keylen); 38 | static void secp256k1_rfc6979_hmac_sha256_generate(secp256k1_rfc6979_hmac_sha256_t *rng, unsigned char *out, size_t outlen); 39 | static void secp256k1_rfc6979_hmac_sha256_finalize(secp256k1_rfc6979_hmac_sha256_t *rng); 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/java/org/bitcoin/NativeSecp256k1Util.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2016 the libsecp256k1 contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.bitcoin; 18 | 19 | public class NativeSecp256k1Util{ 20 | 21 | public static void assertEquals( int val, int val2, String message ) throws AssertFailException{ 22 | if( val != val2 ) 23 | throw new AssertFailException("FAIL: " + message); 24 | } 25 | 26 | public static void assertEquals( boolean val, boolean val2, String message ) throws AssertFailException{ 27 | if( val != val2 ) 28 | throw new AssertFailException("FAIL: " + message); 29 | else 30 | System.out.println("PASS: " + message); 31 | } 32 | 33 | public static void assertEquals( String val, String val2, String message ) throws AssertFailException{ 34 | if( !val.equals(val2) ) 35 | throw new AssertFailException("FAIL: " + message); 36 | else 37 | System.out.println("PASS: " + message); 38 | } 39 | 40 | public static class AssertFailException extends Exception { 41 | public AssertFailException(String message) { 42 | super( message ); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/java/org/bitcoin/Secp256k1Context.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2016 the libsecp256k1 contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.bitcoin; 18 | 19 | /** 20 | * This class holds the context reference used in native methods 21 | * to handle ECDSA operations. 22 | */ 23 | public class Secp256k1Context { 24 | private static final boolean enabled; //true if the library is loaded 25 | private static final long context; //ref to pointer to context obj 26 | 27 | static { //static initializer 28 | boolean isEnabled = true; 29 | long contextRef = -1; 30 | try { 31 | System.loadLibrary("secp256k1"); 32 | contextRef = secp256k1_init_context(); 33 | } catch (UnsatisfiedLinkError e) { 34 | System.out.println("UnsatisfiedLinkError: " + e.toString()); 35 | isEnabled = false; 36 | } 37 | enabled = isEnabled; 38 | context = contextRef; 39 | } 40 | 41 | public static boolean isEnabled() { 42 | return enabled; 43 | } 44 | 45 | public static long getContext() { 46 | if(!enabled) return -1; //sanity check 47 | return context; 48 | } 49 | 50 | private static native long secp256k1_init_context(); 51 | } 52 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/java/org_bitcoin_Secp256k1Context.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "org_bitcoin_Secp256k1Context.h" 4 | #include "include/secp256k1.h" 5 | 6 | SECP256K1_API jlong JNICALL Java_org_bitcoin_Secp256k1Context_secp256k1_1init_1context 7 | (JNIEnv* env, jclass classObject) 8 | { 9 | secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); 10 | 11 | (void)classObject;(void)env; 12 | 13 | return (uintptr_t)ctx; 14 | } 15 | 16 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/java/org_bitcoin_Secp256k1Context.h: -------------------------------------------------------------------------------- 1 | /* DO NOT EDIT THIS FILE - it is machine generated */ 2 | #include 3 | #include "include/secp256k1.h" 4 | /* Header for class org_bitcoin_Secp256k1Context */ 5 | 6 | #ifndef _Included_org_bitcoin_Secp256k1Context 7 | #define _Included_org_bitcoin_Secp256k1Context 8 | #ifdef __cplusplus 9 | extern "C" { 10 | #endif 11 | /* 12 | * Class: org_bitcoin_Secp256k1Context 13 | * Method: secp256k1_init_context 14 | * Signature: ()J 15 | */ 16 | SECP256K1_API jlong JNICALL Java_org_bitcoin_Secp256k1Context_secp256k1_1init_1context 17 | (JNIEnv *, jclass); 18 | 19 | #ifdef __cplusplus 20 | } 21 | #endif 22 | #endif 23 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/modules/ecdh/Makefile.am.include: -------------------------------------------------------------------------------- 1 | include_HEADERS += include/secp256k1_ecdh.h 2 | noinst_HEADERS += src/modules/ecdh/main_impl.h 3 | noinst_HEADERS += src/modules/ecdh/tests_impl.h 4 | if USE_BENCHMARK 5 | noinst_PROGRAMS += bench_ecdh 6 | bench_ecdh_SOURCES = src/bench_ecdh.c 7 | bench_ecdh_LDADD = libsecp256k1.la $(SECP_LIBS) $(COMMON_LIB) 8 | endif 9 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/modules/ecdh/main_impl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_MODULE_ECDH_MAIN_ 8 | #define _SECP256K1_MODULE_ECDH_MAIN_ 9 | 10 | #include "include/secp256k1_ecdh.h" 11 | #include "ecmult_const_impl.h" 12 | 13 | int secp256k1_ecdh(const secp256k1_context* ctx, unsigned char *result, const secp256k1_pubkey *point, const unsigned char *scalar) { 14 | int ret = 0; 15 | int overflow = 0; 16 | secp256k1_gej res; 17 | secp256k1_ge pt; 18 | secp256k1_scalar s; 19 | VERIFY_CHECK(ctx != NULL); 20 | ARG_CHECK(result != NULL); 21 | ARG_CHECK(point != NULL); 22 | ARG_CHECK(scalar != NULL); 23 | 24 | secp256k1_pubkey_load(ctx, &pt, point); 25 | secp256k1_scalar_set_b32(&s, scalar, &overflow); 26 | if (overflow || secp256k1_scalar_is_zero(&s)) { 27 | ret = 0; 28 | } else { 29 | unsigned char x[32]; 30 | unsigned char y[1]; 31 | secp256k1_sha256_t sha; 32 | 33 | secp256k1_ecmult_const(&res, &pt, &s); 34 | secp256k1_ge_set_gej(&pt, &res); 35 | /* Compute a hash of the point in compressed form 36 | * Note we cannot use secp256k1_eckey_pubkey_serialize here since it does not 37 | * expect its output to be secret and has a timing sidechannel. */ 38 | secp256k1_fe_normalize(&pt.x); 39 | secp256k1_fe_normalize(&pt.y); 40 | secp256k1_fe_get_b32(x, &pt.x); 41 | y[0] = 0x02 | secp256k1_fe_is_odd(&pt.y); 42 | 43 | secp256k1_sha256_initialize(&sha); 44 | secp256k1_sha256_write(&sha, y, sizeof(y)); 45 | secp256k1_sha256_write(&sha, x, sizeof(x)); 46 | secp256k1_sha256_finalize(&sha, result); 47 | ret = 1; 48 | } 49 | 50 | secp256k1_scalar_clear(&s); 51 | return ret; 52 | } 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/modules/recovery/Makefile.am.include: -------------------------------------------------------------------------------- 1 | include_HEADERS += include/secp256k1_recovery.h 2 | noinst_HEADERS += src/modules/recovery/main_impl.h 3 | noinst_HEADERS += src/modules/recovery/tests_impl.h 4 | if USE_BENCHMARK 5 | noinst_PROGRAMS += bench_recover 6 | bench_recover_SOURCES = src/bench_recover.c 7 | bench_recover_LDADD = libsecp256k1.la $(SECP_LIBS) $(COMMON_LIB) 8 | endif 9 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/num_gmp.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_NUM_REPR_ 8 | #define _SECP256K1_NUM_REPR_ 9 | 10 | #include 11 | 12 | #define NUM_LIMBS ((256+GMP_NUMB_BITS-1)/GMP_NUMB_BITS) 13 | 14 | typedef struct { 15 | mp_limb_t data[2*NUM_LIMBS]; 16 | int neg; 17 | int limbs; 18 | } secp256k1_num; 19 | 20 | #endif 21 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/num_impl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_NUM_IMPL_H_ 8 | #define _SECP256K1_NUM_IMPL_H_ 9 | 10 | #if defined HAVE_CONFIG_H 11 | #include "libsecp256k1-config.h" 12 | #endif 13 | 14 | #include "num.h" 15 | 16 | #if defined(USE_NUM_GMP) 17 | #include "num_gmp_impl.h" 18 | #elif defined(USE_NUM_NONE) 19 | /* Nothing. */ 20 | #else 21 | #error "Please select num implementation" 22 | #endif 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/scalar_4x64.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_SCALAR_REPR_ 8 | #define _SECP256K1_SCALAR_REPR_ 9 | 10 | #include 11 | 12 | /** A scalar modulo the group order of the secp256k1 curve. */ 13 | typedef struct { 14 | uint64_t d[4]; 15 | } secp256k1_scalar; 16 | 17 | #define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/scalar_8x32.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_SCALAR_REPR_ 8 | #define _SECP256K1_SCALAR_REPR_ 9 | 10 | #include 11 | 12 | /** A scalar modulo the group order of the secp256k1 curve. */ 13 | typedef struct { 14 | uint32_t d[8]; 15 | } secp256k1_scalar; 16 | 17 | #define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/scalar_low.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_SCALAR_REPR_ 8 | #define _SECP256K1_SCALAR_REPR_ 9 | 10 | #include 11 | 12 | /** A scalar modulo the group order of the secp256k1 curve. */ 13 | typedef uint32_t secp256k1_scalar; 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/libsecp256k1/src/testrand.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_TESTRAND_H_ 8 | #define _SECP256K1_TESTRAND_H_ 9 | 10 | #if defined HAVE_CONFIG_H 11 | #include "libsecp256k1-config.h" 12 | #endif 13 | 14 | /* A non-cryptographic RNG used only for test infrastructure. */ 15 | 16 | /** Seed the pseudorandom number generator for testing. */ 17 | SECP256K1_INLINE static void secp256k1_rand_seed(const unsigned char *seed16); 18 | 19 | /** Generate a pseudorandom number in the range [0..2**32-1]. */ 20 | static uint32_t secp256k1_rand32(void); 21 | 22 | /** Generate a pseudorandom number in the range [0..2**bits-1]. Bits must be 1 or 23 | * more. */ 24 | static uint32_t secp256k1_rand_bits(int bits); 25 | 26 | /** Generate a pseudorandom number in the range [0..range-1]. */ 27 | static uint32_t secp256k1_rand_int(uint32_t range); 28 | 29 | /** Generate a pseudorandom 32-byte array. */ 30 | static void secp256k1_rand256(unsigned char *b32); 31 | 32 | /** Generate a pseudorandom 32-byte array with long sequences of zero and one bits. */ 33 | static void secp256k1_rand256_test(unsigned char *b32); 34 | 35 | /** Generate pseudorandom bytes with long sequences of zero and one bits. */ 36 | static void secp256k1_rand_bytes_test(unsigned char *bytes, size_t len); 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /common/crypto/secp256k1/panic_cb.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package secp256k1 18 | 19 | import "C" 20 | import "unsafe" 21 | 22 | // Callbacks for converting libsecp256k1 internal faults into 23 | // recoverable Go panics. 24 | 25 | //export secp256k1GoPanicIllegal 26 | func secp256k1GoPanicIllegal(msg *C.char, data unsafe.Pointer) { 27 | panic("illegal argument: " + C.GoString(msg)) 28 | } 29 | 30 | //export secp256k1GoPanicError 31 | func secp256k1GoPanicError(msg *C.char, data unsafe.Pointer) { 32 | panic("internal error: " + C.GoString(msg)) 33 | } 34 | -------------------------------------------------------------------------------- /common/crypto/signature_cgo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // +build !nacl,!js,!nocgo 18 | 19 | package crypto 20 | 21 | import ( 22 | "crypto/ecdsa" 23 | "crypto/elliptic" 24 | "fmt" 25 | "github.com/traceabilitychain/tacchain/common/crypto/secp256k1" 26 | ) 27 | 28 | 29 | func Ecrecover(hash, sig []byte) ([]byte, error) { 30 | return secp256k1.RecoverPubkey(hash, sig) 31 | } 32 | 33 | func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) { 34 | s, err := Ecrecover(hash, sig) 35 | if err != nil { 36 | return nil, err 37 | } 38 | 39 | x, y := elliptic.Unmarshal(S256(), s) 40 | return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil 41 | } 42 | 43 | // Sign calculates an ECDSA signature. 44 | // 45 | // This function is susceptible to chosen plaintext attacks that can leak 46 | // information about the private key that is used for signing. Callers must 47 | // be aware that the given hash cannot be chosen by an adversery. Common 48 | // solution is to hash any input before calculating the signature. 49 | // 50 | // The produced signature is in the [R || S || V] format where V is 0 or 1. 51 | func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) { 52 | if len(hash) != 32 { 53 | return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash)) 54 | } 55 | seckey := secp256k1.PaddedBigBytes(prv.D, prv.Params().BitSize/8) 56 | defer zeroBytes(seckey) 57 | return secp256k1.Sign(hash, seckey) 58 | } 59 | 60 | // S256 returns an instance of the secp256k1 curve. 61 | func S256() elliptic.Curve { 62 | return secp256k1.S256() 63 | } 64 | 65 | func zeroBytes(bytes []byte) { 66 | for i := range bytes { 67 | bytes[i] = 0 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /common/crypto/signer.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package crypto 18 | 19 | import cb "github.com/traceabilitychain/tacchain/protos/common" 20 | 21 | // LocalSigner is a temporary stub interface which will be implemented by the local MSP 22 | type LocalSigner interface { 23 | // NewSignatureHeader creates a SignatureHeader with the correct signing identity and a valid nonce 24 | NewSignatureHeader() (*cb.SignatureHeader, error) 25 | 26 | // Sign a message which should embed a signature header created by NewSignatureHeader 27 | Sign(message []byte) ([]byte, error) 28 | } 29 | -------------------------------------------------------------------------------- /common/flogging/grpclogger.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package flogging 18 | 19 | import ( 20 | "github.com/op/go-logging" 21 | "google.golang.org/grpc/grpclog" 22 | ) 23 | 24 | const GRPCModuleID = "grpc" 25 | 26 | func initgrpclogger() { 27 | glogger := MustGetLogger(GRPCModuleID) 28 | grpclog.SetLogger(&grpclogger{glogger}) 29 | } 30 | 31 | // grpclogger implements the standard Go logging interface and wraps the 32 | // logger provided by the flogging package. This is required in order to 33 | // replace the default log used by the grpclog package. 34 | type grpclogger struct { 35 | logger *logging.Logger 36 | } 37 | 38 | func (g *grpclogger) Fatal(args ...interface{}) { 39 | g.logger.Fatal(args...) 40 | } 41 | 42 | func (g *grpclogger) Fatalf(format string, args ...interface{}) { 43 | g.logger.Fatalf(format, args...) 44 | } 45 | 46 | func (g *grpclogger) Fatalln(args ...interface{}) { 47 | g.logger.Fatal(args...) 48 | } 49 | 50 | // NOTE: grpclog does not support leveled logs so for now use DEBUG 51 | func (g *grpclogger) Print(args ...interface{}) { 52 | g.logger.Debug(args...) 53 | } 54 | 55 | func (g *grpclogger) Printf(format string, args ...interface{}) { 56 | g.logger.Debugf(format, args...) 57 | } 58 | 59 | func (g *grpclogger) Println(args ...interface{}) { 60 | g.logger.Debug(args...) 61 | } 62 | -------------------------------------------------------------------------------- /common/flogging/grpclogger_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package flogging 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/op/go-logging" 23 | "github.com/stretchr/testify/assert" 24 | "google.golang.org/grpc/grpclog" 25 | ) 26 | 27 | // from go-logging memory_test.go 28 | func MemoryRecordN(b *logging.MemoryBackend, n int) *logging.Record { 29 | node := b.Head() 30 | for i := 0; i < n; i++ { 31 | if node == nil { 32 | break 33 | } 34 | node = node.Next() 35 | } 36 | if node == nil { 37 | return nil 38 | } 39 | return node.Record 40 | } 41 | 42 | func TestGRPCLogger(t *testing.T) { 43 | initgrpclogger() 44 | backend := logging.NewMemoryBackend(3) 45 | logging.SetBackend(backend) 46 | logging.SetLevel(defaultLevel, "") 47 | SetModuleLevel(GRPCModuleID, "DEBUG") 48 | messages := []string{"print test", "printf test", "println test"} 49 | grpclog.Print(messages[0]) 50 | grpclog.Printf(messages[1]) 51 | grpclog.Println(messages[2]) 52 | 53 | for i, message := range messages { 54 | assert.Equal(t, message, MemoryRecordN(backend, i).Message()) 55 | t.Log(MemoryRecordN(backend, i).Message()) 56 | } 57 | 58 | // now make sure there's no logging at a level other than DEBUG 59 | SetModuleLevel(GRPCModuleID, "INFO") 60 | messages2 := []string{"print test2", "printf test2", "println test2"} 61 | grpclog.Print(messages2[0]) 62 | grpclog.Printf(messages2[1]) 63 | grpclog.Println(messages2[2]) 64 | 65 | // should still be messages not messages2 66 | for i, message := range messages { 67 | assert.Equal(t, message, MemoryRecordN(backend, i).Message()) 68 | t.Log(MemoryRecordN(backend, i).Message()) 69 | } 70 | // reset flogging 71 | Reset() 72 | } 73 | -------------------------------------------------------------------------------- /common/genesis/genesis_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package genesis 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/traceabilitychain/tacchain/common/configtx" 23 | "github.com/traceabilitychain/tacchain/protos/utils" 24 | "github.com/stretchr/testify/assert" 25 | ) 26 | 27 | func TestBasicSanity(t *testing.T) { 28 | impl := NewFactoryImpl(configtx.NewSimpleTemplate()) 29 | _, err := impl.Block("testchainid") 30 | assert.NoError(t, err, "Basic sanity fails") 31 | } 32 | 33 | func TestForTransactionID(t *testing.T) { 34 | impl := NewFactoryImpl(configtx.NewSimpleTemplate()) 35 | block, _ := impl.Block("testchainid") 36 | configEnv, _ := utils.ExtractEnvelope(block, 0) 37 | configEnvPayload, _ := utils.ExtractPayload(configEnv) 38 | configEnvPayloadChannelHeader, _ := utils.UnmarshalChannelHeader(configEnvPayload.GetHeader().ChannelHeader) 39 | assert.NotEmpty(t, configEnvPayloadChannelHeader.TxId, "tx_id of configuration transaction should not be empty") 40 | } 41 | -------------------------------------------------------------------------------- /common/ledger/blkstorage/fsblkstorage/block_serialization_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package fsblkstorage 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/golang/protobuf/proto" 23 | "github.com/traceabilitychain/tacchain/common/ledger/testutil" 24 | putils "github.com/traceabilitychain/tacchain/protos/utils" 25 | ) 26 | 27 | func TestBlockSerialization(t *testing.T) { 28 | block := testutil.ConstructTestBlock(t, 1, 10, 100) 29 | bb, _, err := serializeBlock(block) 30 | testutil.AssertNoError(t, err, "") 31 | deserializedBlock, err := deserializeBlock(bb) 32 | testutil.AssertNoError(t, err, "") 33 | testutil.AssertEquals(t, deserializedBlock, block) 34 | } 35 | 36 | func TestExtractTxid(t *testing.T) { 37 | txEnv, txid, _ := testutil.ConstructTransaction(t, testutil.ConstructRandomBytes(t, 50), false) 38 | txEnvBytes, _ := putils.GetBytesEnvelope(txEnv) 39 | extractedTxid, err := extractTxID(txEnvBytes) 40 | testutil.AssertNoError(t, err, "") 41 | testutil.AssertEquals(t, extractedTxid, txid) 42 | } 43 | 44 | func TestSerializedBlockInfo(t *testing.T) { 45 | block := testutil.ConstructTestBlock(t, 1, 10, 100) 46 | bb, info, err := serializeBlock(block) 47 | testutil.AssertNoError(t, err, "") 48 | infoFromBB, err := extractSerializedBlockInfo(bb) 49 | testutil.AssertNoError(t, err, "") 50 | testutil.AssertEquals(t, infoFromBB, info) 51 | testutil.AssertEquals(t, len(info.txOffsets), len(block.Data.Data)) 52 | for txIndex, txEnvBytes := range block.Data.Data { 53 | txid, err := extractTxID(txEnvBytes) 54 | testutil.AssertNoError(t, err, "") 55 | 56 | indexInfo := info.txOffsets[txIndex] 57 | indexTxID := indexInfo.txID 58 | indexOffset := indexInfo.loc 59 | 60 | testutil.AssertEquals(t, txid, indexTxID) 61 | b := bb[indexOffset.offset:] 62 | len, num := proto.DecodeVarint(b) 63 | txEnvBytesFromBB := b[num : num+int(len)] 64 | testutil.AssertEquals(t, txEnvBytesFromBB, txEnvBytes) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /common/ledger/blkstorage/fsblkstorage/blockfile_rw.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package fsblkstorage 18 | 19 | import ( 20 | "os" 21 | ) 22 | 23 | //// WRITER //// 24 | type blockfileWriter struct { 25 | filePath string 26 | file *os.File 27 | } 28 | 29 | func newBlockfileWriter(filePath string) (*blockfileWriter, error) { 30 | writer := &blockfileWriter{filePath: filePath} 31 | return writer, writer.open() 32 | } 33 | 34 | func (w *blockfileWriter) truncateFile(targetSize int) error { 35 | fileStat, err := w.file.Stat() 36 | if err != nil { 37 | return err 38 | } 39 | if fileStat.Size() > int64(targetSize) { 40 | w.file.Truncate(int64(targetSize)) 41 | } 42 | return nil 43 | } 44 | 45 | func (w *blockfileWriter) append(b []byte, sync bool) error { 46 | _, err := w.file.Write(b) 47 | if err != nil { 48 | return err 49 | } 50 | if sync { 51 | return w.file.Sync() 52 | } 53 | return nil 54 | } 55 | 56 | func (w *blockfileWriter) open() error { 57 | file, err := os.OpenFile(w.filePath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660) 58 | if err != nil { 59 | return err 60 | } 61 | w.file = file 62 | return nil 63 | } 64 | 65 | func (w *blockfileWriter) close() error { 66 | return w.file.Close() 67 | } 68 | 69 | //// READER //// 70 | type blockfileReader struct { 71 | file *os.File 72 | } 73 | 74 | func newBlockfileReader(filePath string) (*blockfileReader, error) { 75 | file, err := os.OpenFile(filePath, os.O_RDONLY, 0600) 76 | if err != nil { 77 | return nil, err 78 | } 79 | reader := &blockfileReader{file} 80 | return reader, nil 81 | } 82 | 83 | func (r *blockfileReader) read(offset int, length int) ([]byte, error) { 84 | b := make([]byte, length) 85 | _, err := r.file.ReadAt(b, int64(offset)) 86 | if err != nil { 87 | return nil, err 88 | } 89 | return b, nil 90 | } 91 | 92 | func (r *blockfileReader) close() error { 93 | return r.file.Close() 94 | } 95 | -------------------------------------------------------------------------------- /common/ledger/blkstorage/fsblkstorage/config.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package fsblkstorage 18 | 19 | import "path/filepath" 20 | 21 | const ( 22 | // ChainsDir is the name of the directory containing the channel ledgers. 23 | ChainsDir = "chains" 24 | // IndexDir is the name of the directory containing all block indexes across ledgers. 25 | IndexDir = "index" 26 | defaultMaxBlockfileSize = 64 * 1024 * 1024 // bytes 27 | ) 28 | 29 | // Conf encapsulates all the configurations for `FsBlockStore` 30 | type Conf struct { 31 | blockStorageDir string 32 | maxBlockfileSize int 33 | } 34 | 35 | // NewConf constructs new `Conf`. 36 | // blockStorageDir is the top level folder under which `FsBlockStore` manages its data 37 | func NewConf(blockStorageDir string, maxBlockfileSize int) *Conf { 38 | if maxBlockfileSize <= 0 { 39 | maxBlockfileSize = defaultMaxBlockfileSize 40 | } 41 | return &Conf{blockStorageDir, maxBlockfileSize} 42 | } 43 | 44 | func (conf *Conf) getIndexDir() string { 45 | return filepath.Join(conf.blockStorageDir, IndexDir) 46 | } 47 | 48 | func (conf *Conf) getChainsDir() string { 49 | return filepath.Join(conf.blockStorageDir, ChainsDir) 50 | } 51 | 52 | func (conf *Conf) getLedgerBlockDir(ledgerid string) string { 53 | return filepath.Join(conf.getChainsDir(), ledgerid) 54 | } 55 | -------------------------------------------------------------------------------- /common/ledger/blkstorage/fsblkstorage/fs_blockstore_provider.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package fsblkstorage 18 | 19 | import ( 20 | "github.com/traceabilitychain/tacchain/common/ledger/blkstorage" 21 | "github.com/traceabilitychain/tacchain/common/ledger/util" 22 | "github.com/traceabilitychain/tacchain/common/ledger/util/leveldbhelper" 23 | ) 24 | 25 | // FsBlockstoreProvider provides handle to block storage - this is not thread-safe 26 | type FsBlockstoreProvider struct { 27 | conf *Conf 28 | indexConfig *blkstorage.IndexConfig 29 | leveldbProvider *leveldbhelper.Provider 30 | } 31 | 32 | // NewProvider constructs a filesystem based block store provider 33 | func NewProvider(conf *Conf, indexConfig *blkstorage.IndexConfig) blkstorage.BlockStoreProvider { 34 | p := leveldbhelper.NewProvider(&leveldbhelper.Conf{DBPath: conf.getIndexDir()}) 35 | return &FsBlockstoreProvider{conf, indexConfig, p} 36 | } 37 | 38 | // CreateBlockStore simply calls OpenBlockStore 39 | func (p *FsBlockstoreProvider) CreateBlockStore(ledgerid string) (blkstorage.BlockStore, error) { 40 | return p.OpenBlockStore(ledgerid) 41 | } 42 | 43 | // OpenBlockStore opens a block store for given ledgerid. 44 | // If a blockstore is not existing, this method creates one 45 | // This method should be invoked only once for a particular ledgerid 46 | func (p *FsBlockstoreProvider) OpenBlockStore(ledgerid string) (blkstorage.BlockStore, error) { 47 | indexStoreHandle := p.leveldbProvider.GetDBHandle(ledgerid) 48 | return newFsBlockStore(ledgerid, p.conf, p.indexConfig, indexStoreHandle), nil 49 | } 50 | 51 | // Exists tells whether the BlockStore with given id exists 52 | func (p *FsBlockstoreProvider) Exists(ledgerid string) (bool, error) { 53 | exists, _, err := util.FileExists(p.conf.getLedgerBlockDir(ledgerid)) 54 | return exists, err 55 | } 56 | 57 | // List lists the ids of the existing ledgers 58 | func (p *FsBlockstoreProvider) List() ([]string, error) { 59 | return util.ListSubdirs(p.conf.getChainsDir()) 60 | } 61 | 62 | // Close closes the FsBlockstoreProvider 63 | func (p *FsBlockstoreProvider) Close() { 64 | p.leveldbProvider.Close() 65 | } 66 | -------------------------------------------------------------------------------- /common/ledger/blkstorage/fsblkstorage/fs_blockstore_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package fsblkstorage 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/traceabilitychain/tacchain/common/ledger/testutil" 23 | ) 24 | 25 | func TestWrongBlockNumber(t *testing.T) { 26 | env := newTestEnv(t, NewConf(testPath(), 0)) 27 | defer env.Cleanup() 28 | 29 | provider := env.provider 30 | store, _ := provider.OpenBlockStore("testLedger") 31 | defer store.Shutdown() 32 | 33 | blocks := testutil.ConstructTestBlocks(t, 5) 34 | for i := 0; i < 3; i++ { 35 | err := store.AddBlock(blocks[i]) 36 | testutil.AssertNoError(t, err, "") 37 | } 38 | err := store.AddBlock(blocks[4]) 39 | testutil.AssertError(t, err, "Error shold have been thrown when adding block number 4 while block number 3 is expected") 40 | } 41 | -------------------------------------------------------------------------------- /common/ledger/ledger_interface.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package ledger 18 | 19 | import ( 20 | "github.com/traceabilitychain/tacchain/protos/common" 21 | ) 22 | 23 | // Ledger captures the methods that are common across the 'PeerLedger', 'OrdererLedger', and 'ValidatedLedger' 24 | type Ledger interface { 25 | // GetBlockchainInfo returns basic info about blockchain 26 | GetBlockchainInfo() (*common.BlockchainInfo, error) 27 | // GetBlockByNumber returns block at a given height 28 | // blockNumber of math.MaxUint64 will return last block 29 | GetBlockByNumber(blockNumber uint64) (*common.Block, error) 30 | // GetBlockWithHashByNumber returns block and hash at a given height 31 | GetBlockWithHashByNumber(blockNumber uint64) (*common.ProcessedBlock, error) 32 | // GetBlocksIterator returns an iterator that starts from `startBlockNumber`(inclusive). 33 | // The iterator is a blocking iterator i.e., it blocks till the next block gets available in the ledger 34 | // ResultsIterator contains type BlockHolder 35 | GetBlocksIterator(startBlockNumber uint64) (ResultsIterator, error) 36 | // Close closes the ledger 37 | Close() 38 | // Commit adds a new block 39 | Commit(block *common.Block) error 40 | } 41 | 42 | // ResultsIterator - an iterator for query result set 43 | type ResultsIterator interface { 44 | // Next returns the next item in the result set. The `QueryResult` is expected to be nil when 45 | // the iterator gets exhausted 46 | Next() (QueryResult, error) 47 | // Close releases resources occupied by the iterator 48 | Close() 49 | } 50 | 51 | // QueryResult - a general interface for supporting different types of query results. Actual types differ for different queries 52 | type QueryResult interface{} 53 | 54 | // PrunePolicy - a general interface for supporting different pruning policies 55 | type PrunePolicy interface{} 56 | -------------------------------------------------------------------------------- /common/ledger/testutil/test_util_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package testutil 18 | 19 | import "testing" 20 | 21 | func TestSkipAll(t *testing.T) { 22 | t.Skip(`No tests in this package for now - This package contains only utility functions that are meant to be used by other functional tests`) 23 | } 24 | -------------------------------------------------------------------------------- /common/ledger/util/leveldbhelper/pkg_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package leveldbhelper 18 | 19 | import ( 20 | "os" 21 | "testing" 22 | 23 | "github.com/traceabilitychain/tacchain/common/ledger/testutil" 24 | ) 25 | 26 | const testDBPath = "/tmp/tacchain/ledgertests/util/leveldbhelper" 27 | 28 | type testDBEnv struct { 29 | t *testing.T 30 | path string 31 | db *DB 32 | } 33 | 34 | type testDBProviderEnv struct { 35 | t *testing.T 36 | path string 37 | provider *Provider 38 | } 39 | 40 | func newTestDBEnv(t *testing.T, path string) *testDBEnv { 41 | testDBEnv := &testDBEnv{t: t, path: path} 42 | testDBEnv.cleanup() 43 | testDBEnv.db = CreateDB(&Conf{path}) 44 | return testDBEnv 45 | } 46 | 47 | func newTestProviderEnv(t *testing.T, path string) *testDBProviderEnv { 48 | testProviderEnv := &testDBProviderEnv{t: t, path: path} 49 | testProviderEnv.cleanup() 50 | testProviderEnv.provider = NewProvider(&Conf{path}) 51 | return testProviderEnv 52 | } 53 | 54 | func (dbEnv *testDBEnv) cleanup() { 55 | if dbEnv.db != nil { 56 | dbEnv.db.Close() 57 | } 58 | testutil.AssertNoError(dbEnv.t, os.RemoveAll(dbEnv.path), "") 59 | } 60 | 61 | func (providerEnv *testDBProviderEnv) cleanup() { 62 | if providerEnv.provider != nil { 63 | providerEnv.provider.Close() 64 | } 65 | testutil.AssertNoError(providerEnv.t, os.RemoveAll(providerEnv.path), "") 66 | } 67 | -------------------------------------------------------------------------------- /common/ledger/util/protobuf_util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package util 18 | 19 | import ( 20 | "github.com/golang/protobuf/proto" 21 | ) 22 | 23 | // Buffer provides a wrapper on top of proto.Buffer. 24 | // The purpose of this wrapper is to get to know the current position in the []byte 25 | type Buffer struct { 26 | buf *proto.Buffer 27 | position int 28 | } 29 | 30 | // NewBuffer constructs a new instance of Buffer 31 | func NewBuffer(b []byte) *Buffer { 32 | return &Buffer{proto.NewBuffer(b), 0} 33 | } 34 | 35 | // DecodeVarint wraps the actual method and updates the position 36 | func (b *Buffer) DecodeVarint() (uint64, error) { 37 | val, err := b.buf.DecodeVarint() 38 | if err == nil { 39 | b.position += proto.SizeVarint(val) 40 | } 41 | return val, err 42 | } 43 | 44 | // DecodeRawBytes wraps the actual method and updates the position 45 | func (b *Buffer) DecodeRawBytes(alloc bool) ([]byte, error) { 46 | val, err := b.buf.DecodeRawBytes(alloc) 47 | if err == nil { 48 | b.position += proto.SizeVarint(uint64(len(val))) + len(val) 49 | } 50 | return val, err 51 | } 52 | 53 | // GetBytesConsumed returns the offset of the current position in the underlying []byte 54 | func (b *Buffer) GetBytesConsumed() int { 55 | return b.position 56 | } 57 | -------------------------------------------------------------------------------- /common/ledger/util/protobuf_util_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package util 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/golang/protobuf/proto" 23 | "github.com/traceabilitychain/tacchain/common/ledger/testutil" 24 | ) 25 | 26 | func TestBuffer(t *testing.T) { 27 | pb := proto.NewBuffer(nil) 28 | pb.EncodeVarint(10) 29 | pos1 := len(pb.Bytes()) 30 | pb.EncodeRawBytes([]byte("JunkText")) 31 | pos2 := len(pb.Bytes()) 32 | pb.EncodeRawBytes([]byte("YetAnotherJunkText")) 33 | pos3 := len(pb.Bytes()) 34 | pb.EncodeVarint(1000000) 35 | pos4 := len(pb.Bytes()) 36 | 37 | b := NewBuffer(pb.Bytes()) 38 | b.DecodeVarint() 39 | testutil.AssertEquals(t, b.GetBytesConsumed(), pos1) 40 | b.DecodeRawBytes(false) 41 | testutil.AssertEquals(t, b.GetBytesConsumed(), pos2) 42 | b.DecodeRawBytes(false) 43 | testutil.AssertEquals(t, b.GetBytesConsumed(), pos3) 44 | b.DecodeVarint() 45 | testutil.AssertEquals(t, b.GetBytesConsumed(), pos4) 46 | } 47 | -------------------------------------------------------------------------------- /common/ledger/util/util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package util 18 | 19 | import ( 20 | "encoding/binary" 21 | "fmt" 22 | 23 | "github.com/golang/protobuf/proto" 24 | ) 25 | 26 | // EncodeOrderPreservingVarUint64 returns a byte-representation for a uint64 number such that 27 | // all zero-bits starting bytes are trimmed in order to reduce the length of the array 28 | // For preserving the order in a default bytes-comparison, first byte contains the number of remaining bytes. 29 | // The presence of first byte also allows to use the returned bytes as part of other larger byte array such as a 30 | // composite-key representation in db 31 | func EncodeOrderPreservingVarUint64(number uint64) []byte { 32 | bytes := make([]byte, 8) 33 | binary.BigEndian.PutUint64(bytes, number) 34 | startingIndex := 0 35 | size := 0 36 | for i, b := range bytes { 37 | if b != 0x00 { 38 | startingIndex = i 39 | size = 8 - i 40 | break 41 | } 42 | } 43 | sizeBytes := proto.EncodeVarint(uint64(size)) 44 | if len(sizeBytes) > 1 { 45 | panic(fmt.Errorf("[]sizeBytes should not be more than one byte because the max number it needs to hold is 8. size=%d", size)) 46 | } 47 | encodedBytes := make([]byte, size+1) 48 | encodedBytes[0] = sizeBytes[0] 49 | copy(encodedBytes[1:], bytes[startingIndex:]) 50 | return encodedBytes 51 | } 52 | 53 | // DecodeOrderPreservingVarUint64 decodes the number from the bytes obtained from method 'EncodeOrderPreservingVarUint64'. 54 | // Also, returns the number of bytes that are consumed in the process 55 | func DecodeOrderPreservingVarUint64(bytes []byte) (uint64, int) { 56 | s, _ := proto.DecodeVarint(bytes) 57 | size := int(s) 58 | decodedBytes := make([]byte, 8) 59 | copy(decodedBytes[8-size:], bytes[1:size+1]) 60 | numBytesConsumed := size + 1 61 | return binary.BigEndian.Uint64(decodedBytes), numBytesConsumed 62 | } 63 | -------------------------------------------------------------------------------- /common/ledger/util/util_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package util 18 | 19 | import ( 20 | "bytes" 21 | "testing" 22 | ) 23 | 24 | func TestBasicEncodingDecoding(t *testing.T) { 25 | for i := 0; i < 10000; i++ { 26 | value := EncodeOrderPreservingVarUint64(uint64(i)) 27 | nextValue := EncodeOrderPreservingVarUint64(uint64(i + 1)) 28 | if !(bytes.Compare(value, nextValue) < 0) { 29 | t.Fatalf("A smaller integer should result into smaller bytes. Encoded bytes for [%d] is [%x] and for [%d] is [%x]", 30 | i, i+1, value, nextValue) 31 | } 32 | decodedValue, _ := DecodeOrderPreservingVarUint64(value) 33 | if decodedValue != uint64(i) { 34 | t.Fatalf("Value not same after decoding. Original value = [%d], decode value = [%d]", i, decodedValue) 35 | } 36 | } 37 | } 38 | 39 | func TestDecodingAppendedValues(t *testing.T) { 40 | appendedValues := []byte{} 41 | for i := 0; i < 1000; i++ { 42 | appendedValues = append(appendedValues, EncodeOrderPreservingVarUint64(uint64(i))...) 43 | } 44 | 45 | len := 0 46 | value := uint64(0) 47 | for i := 0; i < 1000; i++ { 48 | appendedValues = appendedValues[len:] 49 | value, len = DecodeOrderPreservingVarUint64(appendedValues) 50 | if value != uint64(i) { 51 | t.Fatalf("expected value = [%d], decode value = [%d]", i, value) 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /common/localmsp/signer.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package localmsp 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/traceabilitychain/tacchain/common/crypto" 23 | mspmgmt "github.com/traceabilitychain/tacchain/msp/mgmt" 24 | cb "github.com/traceabilitychain/tacchain/protos/common" 25 | ) 26 | 27 | type mspSigner struct { 28 | } 29 | 30 | // NewSigner returns a new instance of the msp-based LocalSigner. 31 | // It assumes that the local msp has been already initialized. 32 | // Look at mspmgmt.LoadLocalMsp for further information. 33 | func NewSigner() crypto.LocalSigner { 34 | return &mspSigner{} 35 | } 36 | 37 | // NewSignatureHeader creates a SignatureHeader with the correct signing identity and a valid nonce 38 | func (s *mspSigner) NewSignatureHeader() (*cb.SignatureHeader, error) { 39 | signer, err := mspmgmt.GetLocalMSP().GetDefaultSigningIdentity() 40 | if err != nil { 41 | return nil, fmt.Errorf("Failed getting MSP-based signer [%s]", err) 42 | } 43 | 44 | creatorIdentityRaw, err := signer.Serialize() 45 | if err != nil { 46 | return nil, fmt.Errorf("Failed serializing creator public identity [%s]", err) 47 | } 48 | 49 | nonce, err := crypto.GetRandomNonce() 50 | if err != nil { 51 | return nil, fmt.Errorf("Failed creating nonce [%s]", err) 52 | } 53 | 54 | sh := &cb.SignatureHeader{} 55 | sh.Creator = creatorIdentityRaw 56 | sh.Nonce = nonce 57 | 58 | return sh, nil 59 | } 60 | 61 | // Sign a message which should embed a signature header created by NewSignatureHeader 62 | func (s *mspSigner) Sign(message []byte) ([]byte, error) { 63 | signer, err := mspmgmt.GetLocalMSP().GetDefaultSigningIdentity() 64 | if err != nil { 65 | return nil, fmt.Errorf("Failed getting MSP-based signer [%s]", err) 66 | } 67 | 68 | signature, err := signer.Sign(message) 69 | if err != nil { 70 | return nil, fmt.Errorf("Failed generating signature [%s]", err) 71 | } 72 | 73 | return signature, nil 74 | } 75 | -------------------------------------------------------------------------------- /common/localmsp/signer_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package localmsp 18 | 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/traceabilitychain/tacchain/common/crypto" 25 | mspmgmt "github.com/traceabilitychain/tacchain/msp/mgmt" 26 | "github.com/stretchr/testify/assert" 27 | ) 28 | 29 | func TestMain(m *testing.M) { 30 | if err := mspmgmt.LoadDevMsp(); err != nil { 31 | os.Exit(-1) 32 | } 33 | 34 | os.Exit(m.Run()) 35 | } 36 | 37 | func TestNewSigner(t *testing.T) { 38 | signer := NewSigner() 39 | assert.NotNil(t, signer, "Signer must be differentr from nil.") 40 | } 41 | 42 | func TestMspSigner_NewSignatureHeader(t *testing.T) { 43 | signer := NewSigner() 44 | 45 | sh, err := signer.NewSignatureHeader() 46 | if err != nil { 47 | t.Fatalf("Failed creting signature header [%s]", err) 48 | } 49 | 50 | assert.NotNil(t, sh, "SignatureHeader must be different from nil") 51 | assert.Len(t, sh.Nonce, crypto.NonceSize, "SignatureHeader.Nonce must be of length %d", crypto.NonceSize) 52 | 53 | mspIdentity, err := mspmgmt.GetLocalMSP().GetDefaultSigningIdentity() 54 | assert.NoError(t, err, "Failed getting default MSP Identity") 55 | publicIdentity := mspIdentity.GetPublicVersion() 56 | assert.NotNil(t, publicIdentity, "Failed getting default public identity. It must be different from nil.") 57 | publicIdentityRaw, err := publicIdentity.Serialize() 58 | assert.NoError(t, err, "Failed serializing default public identity") 59 | assert.Equal(t, publicIdentityRaw, sh.Creator, "Creator must be local default signer identity") 60 | } 61 | 62 | func TestMspSigner_Sign(t *testing.T) { 63 | signer := NewSigner() 64 | 65 | msg := []byte("Hello World") 66 | sigma, err := signer.Sign(msg) 67 | assert.NoError(t, err, "FAiled generating signature") 68 | 69 | // Verify signature 70 | mspIdentity, err := mspmgmt.GetLocalMSP().GetDefaultSigningIdentity() 71 | assert.NoError(t, err, "Failed getting default MSP Identity") 72 | err = mspIdentity.Verify(msg, sigma) 73 | assert.NoError(t, err, "Failed verifiing signature") 74 | } 75 | -------------------------------------------------------------------------------- /common/metadata/metadata.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright London Stock Exchange 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package metadata 18 | 19 | // Variables defined by the Makefile and passed in with ldflags 20 | var Version string 21 | var BaseVersion string 22 | var BaseDockerLabel string 23 | var DockerNamespace string 24 | var BaseDockerNamespace string 25 | -------------------------------------------------------------------------------- /common/mocks/config/channel.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import "github.com/traceabilitychain/tacchain/common/util" 20 | 21 | func nearIdentityHash(input []byte) []byte { 22 | return util.ConcatenateBytes([]byte("FakeHash("), input, []byte("")) 23 | } 24 | 25 | // Channel is a mock implementation of config.Channel 26 | type Channel struct { 27 | // HashingAlgorithmVal is returned as the result of HashingAlgorithm() if set 28 | HashingAlgorithmVal func([]byte) []byte 29 | // BlockDataHashingStructureWidthVal is returned as the result of BlockDataHashingStructureWidth() 30 | BlockDataHashingStructureWidthVal uint32 31 | // OrdererAddressesVal is returned as the result of OrdererAddresses() 32 | OrdererAddressesVal []string 33 | } 34 | 35 | // HashingAlgorithm returns the HashingAlgorithmVal if set, otherwise a fake simple hash function 36 | func (scm *Channel) HashingAlgorithm() func([]byte) []byte { 37 | if scm.HashingAlgorithmVal == nil { 38 | return nearIdentityHash 39 | } 40 | return scm.HashingAlgorithmVal 41 | } 42 | 43 | // BlockDataHashingStructureWidth returns the BlockDataHashingStructureWidthVal 44 | func (scm *Channel) BlockDataHashingStructureWidth() uint32 { 45 | return scm.BlockDataHashingStructureWidthVal 46 | } 47 | 48 | // OrdererAddresses returns the OrdererAddressesVal 49 | func (scm *Channel) OrdererAddresses() []string { 50 | return scm.OrdererAddressesVal 51 | } 52 | -------------------------------------------------------------------------------- /common/mocks/config/channel_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/traceabilitychain/tacchain/common/config" 23 | ) 24 | 25 | func TestChannelConfigInterface(t *testing.T) { 26 | _ = config.Channel(&Channel{}) 27 | } 28 | -------------------------------------------------------------------------------- /common/mocks/config/orderer.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import ( 20 | "time" 21 | 22 | "github.com/traceabilitychain/tacchain/common/config" 23 | ab "github.com/traceabilitychain/tacchain/protos/orderer" 24 | ) 25 | 26 | // Orderer is a mock implementation of config.Orderer 27 | type Orderer struct { 28 | // ConsensusTypeVal is returned as the result of ConsensusType() 29 | ConsensusTypeVal string 30 | // BatchSizeVal is returned as the result of BatchSize() 31 | BatchSizeVal *ab.BatchSize 32 | // BatchTimeoutVal is returned as the result of BatchTimeout() 33 | BatchTimeoutVal time.Duration 34 | // KafkaBrokersVal is returned as the result of KafkaBrokers() 35 | KafkaBrokersVal []string 36 | // MaxChannelsCountVal is returns as the result of MaxChannelsCount() 37 | MaxChannelsCountVal uint64 38 | // OrganizationsVal is returned as the result of Organizations() 39 | OrganizationsVal map[string]config.Org 40 | } 41 | 42 | // ConsensusType returns the ConsensusTypeVal 43 | func (scm *Orderer) ConsensusType() string { 44 | return scm.ConsensusTypeVal 45 | } 46 | 47 | // BatchSize returns the BatchSizeVal 48 | func (scm *Orderer) BatchSize() *ab.BatchSize { 49 | return scm.BatchSizeVal 50 | } 51 | 52 | // BatchTimeout returns the BatchTimeoutVal 53 | func (scm *Orderer) BatchTimeout() time.Duration { 54 | return scm.BatchTimeoutVal 55 | } 56 | 57 | // KafkaBrokers returns the KafkaBrokersVal 58 | func (scm *Orderer) KafkaBrokers() []string { 59 | return scm.KafkaBrokersVal 60 | } 61 | 62 | // MaxChannelsCount returns the MaxChannelsCountVal 63 | func (scm *Orderer) MaxChannelsCount() uint64 { 64 | return scm.MaxChannelsCountVal 65 | } 66 | 67 | // Organizations returns OrganizationsVal 68 | func (scm *Orderer) Organizations() map[string]config.Org { 69 | return scm.OrganizationsVal 70 | } 71 | -------------------------------------------------------------------------------- /common/mocks/config/orderer_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package config 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/traceabilitychain/tacchain/common/config" 23 | ) 24 | 25 | func TestOrdererConfigInterface(t *testing.T) { 26 | _ = config.Orderer(&Orderer{}) 27 | } 28 | -------------------------------------------------------------------------------- /common/mocks/configtx/configtx_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package configtx 18 | 19 | import ( 20 | "testing" 21 | 22 | configtxapi "github.com/traceabilitychain/tacchain/common/configtx/api" 23 | "github.com/traceabilitychain/tacchain/common/policies" 24 | ) 25 | 26 | func TestConfigtxTransactionalInterface(t *testing.T) { 27 | _ = configtxapi.Transactional(&Transactional{}) 28 | } 29 | 30 | func TestConfigtxPolicyProposerInterface(t *testing.T) { 31 | _ = policies.Proposer(&PolicyProposer{}) 32 | } 33 | 34 | func TestConfigtxInitializerInterface(t *testing.T) { 35 | _ = configtxapi.Initializer(&Initializer{}) 36 | } 37 | 38 | func TestConfigtxManagerInterface(t *testing.T) { 39 | _ = configtxapi.Manager(&Manager{}) 40 | } 41 | 42 | func TestConfigtxResourcesInterface(t *testing.T) { 43 | _ = configtxapi.Resources(&Resources{}) 44 | } 45 | -------------------------------------------------------------------------------- /common/mocks/crypto/localsigner.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package crypto 18 | 19 | import ( 20 | cb "github.com/traceabilitychain/tacchain/protos/common" 21 | ) 22 | 23 | // FakeLocalSigner is a signer which already has identity an nonce set to fake values 24 | var FakeLocalSigner = &LocalSigner{ 25 | Identity: []byte("IdentityBytes"), 26 | Nonce: []byte("NonceValue"), 27 | } 28 | 29 | // LocalSigner is a mock implmeentation of crypto.LocalSigner 30 | type LocalSigner struct { 31 | Identity []byte 32 | Nonce []byte 33 | } 34 | 35 | // Sign returns the msg, nil 36 | func (ls *LocalSigner) Sign(msg []byte) ([]byte, error) { 37 | return msg, nil 38 | } 39 | 40 | // NewSignatureHeader returns a new signature header, nil 41 | func (ls *LocalSigner) NewSignatureHeader() (*cb.SignatureHeader, error) { 42 | return &cb.SignatureHeader{ 43 | Creator: ls.Identity, 44 | Nonce: ls.Nonce, 45 | }, nil 46 | } 47 | -------------------------------------------------------------------------------- /common/mocks/crypto/localsigner_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package crypto 18 | 19 | import ( 20 | "testing" 21 | 22 | crypto "github.com/traceabilitychain/tacchain/common/crypto" 23 | ) 24 | 25 | func TestLocalSignerInterface(t *testing.T) { 26 | _ = crypto.LocalSigner(&LocalSigner{}) 27 | } 28 | -------------------------------------------------------------------------------- /common/mocks/ledger/queryexecutor.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package ledger 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/traceabilitychain/tacchain/common/ledger" 23 | ) 24 | 25 | type MockQueryExecutor struct { 26 | // State keeps all namepspaces 27 | State map[string]map[string][]byte 28 | } 29 | 30 | func NewMockQueryExecutor(state map[string]map[string][]byte) *MockQueryExecutor { 31 | return &MockQueryExecutor{ 32 | State: state, 33 | } 34 | } 35 | 36 | func (m *MockQueryExecutor) GetState(namespace string, key string) ([]byte, error) { 37 | ns := m.State[namespace] 38 | if ns == nil { 39 | return nil, fmt.Errorf("Could not retrieve namespace %s", namespace) 40 | } 41 | 42 | return ns[key], nil 43 | } 44 | 45 | func (m *MockQueryExecutor) GetStateMultipleKeys(namespace string, keys []string) ([][]byte, error) { 46 | return nil, nil 47 | 48 | } 49 | 50 | func (m *MockQueryExecutor) GetStateRangeScanIterator(namespace string, startKey string, endKey string) (ledger.ResultsIterator, error) { 51 | return nil, nil 52 | 53 | } 54 | 55 | func (m *MockQueryExecutor) ExecuteQuery(namespace, query string) (ledger.ResultsIterator, error) { 56 | return nil, nil 57 | } 58 | 59 | func (m *MockQueryExecutor) Done() { 60 | 61 | } 62 | -------------------------------------------------------------------------------- /common/policies/implicitmeta.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package policies 18 | 19 | import ( 20 | "fmt" 21 | 22 | cb "github.com/traceabilitychain/tacchain/protos/common" 23 | 24 | "github.com/golang/protobuf/proto" 25 | ) 26 | 27 | type implicitMetaPolicy struct { 28 | conf *cb.ImplicitMetaPolicy 29 | threshold int 30 | subPolicies []Policy 31 | } 32 | 33 | // NewPolicy creates a new policy based on the policy bytes 34 | func newImplicitMetaPolicy(data []byte) (*implicitMetaPolicy, error) { 35 | imp := &cb.ImplicitMetaPolicy{} 36 | if err := proto.Unmarshal(data, imp); err != nil { 37 | return nil, fmt.Errorf("Error unmarshaling to ImplicitMetaPolicy: %s", err) 38 | } 39 | 40 | return &implicitMetaPolicy{ 41 | conf: imp, 42 | }, nil 43 | } 44 | 45 | func (imp *implicitMetaPolicy) initialize(config *policyConfig) { 46 | imp.subPolicies = make([]Policy, len(config.managers)) 47 | i := 0 48 | for _, manager := range config.managers { 49 | imp.subPolicies[i], _ = manager.GetPolicy(imp.conf.SubPolicy) 50 | i++ 51 | } 52 | 53 | switch imp.conf.Rule { 54 | case cb.ImplicitMetaPolicy_ANY: 55 | imp.threshold = 1 56 | case cb.ImplicitMetaPolicy_ALL: 57 | imp.threshold = len(imp.subPolicies) 58 | case cb.ImplicitMetaPolicy_MAJORITY: 59 | imp.threshold = len(imp.subPolicies)/2 + 1 60 | } 61 | 62 | // In the special case that there are no policies, consider 0 to be a majority or any 63 | if len(imp.subPolicies) == 0 { 64 | imp.threshold = 0 65 | } 66 | } 67 | 68 | // Evaluate takes a set of SignedData and evaluates whether this set of signatures satisfies the policy 69 | func (imp *implicitMetaPolicy) Evaluate(signatureSet []*cb.SignedData) error { 70 | remaining := imp.threshold 71 | for _, policy := range imp.subPolicies { 72 | if policy.Evaluate(signatureSet) == nil { 73 | remaining-- 74 | if remaining == 0 { 75 | return nil 76 | } 77 | } 78 | } 79 | if remaining == 0 { 80 | return nil 81 | } 82 | return fmt.Errorf("Failed to reach implicit threshold of %d sub-policies, required %d remaining", imp.threshold, remaining) 83 | } 84 | -------------------------------------------------------------------------------- /common/tools/configtxlator/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "net/http" 22 | "os" 23 | 24 | "github.com/traceabilitychain/tacchain/common/tools/configtxlator/metadata" 25 | "github.com/traceabilitychain/tacchain/common/tools/configtxlator/rest" 26 | "github.com/op/go-logging" 27 | "gopkg.in/alecthomas/kingpin.v2" 28 | ) 29 | 30 | var logger = logging.MustGetLogger("configtxlator") 31 | 32 | // command line flags 33 | var ( 34 | app = kingpin.New("configtxlator", "Utility for generating Tacchain tacchain channel configurations") 35 | 36 | start = app.Command("start", "Start the configtxlator REST server") 37 | hostname = start.Flag("hostname", "The hostname or IP on which the REST server will listen").Default("0.0.0.0").String() 38 | port = start.Flag("port", "The port on which the REST server will listen").Default("7059").Int() 39 | 40 | version = app.Command("version", "Show version information") 41 | ) 42 | 43 | func main() { 44 | kingpin.Version("0.0.1") 45 | switch kingpin.MustParse(app.Parse(os.Args[1:])) { 46 | // "start" command 47 | case start.FullCommand(): 48 | startServer(fmt.Sprintf("%s:%d", *hostname, *port)) 49 | 50 | // "version" command 51 | case version.FullCommand(): 52 | printVersion() 53 | } 54 | 55 | } 56 | 57 | func startServer(address string) { 58 | logger.Infof("Serving HTTP requests on %s", address) 59 | err := http.ListenAndServe(address, rest.NewRouter()) 60 | 61 | app.Fatalf("Error starting server:[%s]\n", err) 62 | } 63 | 64 | func printVersion() { 65 | fmt.Println(metadata.GetVersionInfo()) 66 | } 67 | -------------------------------------------------------------------------------- /common/tools/configtxlator/metadata/metadata.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package metadata 8 | 9 | import ( 10 | "fmt" 11 | "runtime" 12 | ) 13 | 14 | // package-scoped variables 15 | 16 | // Package version 17 | var Version string 18 | 19 | // package-scoped constants 20 | 21 | // Program name 22 | const ProgramName = "configtxlator" 23 | 24 | func GetVersionInfo() string { 25 | if Version == "" { 26 | Version = "development build" 27 | } 28 | 29 | return fmt.Sprintf("%s:\n Version: %s\n Go version: %s\n OS/Arch: %s", 30 | ProgramName, Version, runtime.Version(), 31 | fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)) 32 | } 33 | -------------------------------------------------------------------------------- /common/tools/configtxlator/metadata/metadata_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package metadata_test 8 | 9 | import ( 10 | "fmt" 11 | "runtime" 12 | "testing" 13 | 14 | "github.com/traceabilitychain/tacchain/common/tools/configtxlator/metadata" 15 | "github.com/stretchr/testify/assert" 16 | ) 17 | 18 | func TestGetVersionInfo(t *testing.T) { 19 | testVersion := "TestVersion" 20 | metadata.Version = testVersion 21 | 22 | expected := fmt.Sprintf("%s:\n Version: %s\n Go version: %s\n OS/Arch: %s", 23 | metadata.ProgramName, testVersion, runtime.Version(), 24 | fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)) 25 | assert.Equal(t, expected, metadata.GetVersionInfo()) 26 | } 27 | -------------------------------------------------------------------------------- /common/tools/configtxlator/rest/router.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package rest 18 | 19 | import ( 20 | "github.com/gorilla/mux" 21 | ) 22 | 23 | func NewRouter() *mux.Router { 24 | router := mux.NewRouter().StrictSlash(true) 25 | router. 26 | HandleFunc("/protolator/encode/{msgName}", Encode). 27 | Methods("POST") 28 | 29 | router. 30 | HandleFunc("/protolator/decode/{msgName}", Decode). 31 | Methods("POST") 32 | router. 33 | HandleFunc("/configtxlator/compute/update-from-configs", ComputeUpdateFromConfigs). 34 | Methods("POST") 35 | router. 36 | HandleFunc("/configtxlator/config/verify", SanityCheckConfig). 37 | Methods("POST") 38 | 39 | return router 40 | } 41 | -------------------------------------------------------------------------------- /common/tools/cryptogen/csp/csp.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package csp 17 | 18 | import ( 19 | "crypto" 20 | "crypto/ecdsa" 21 | "crypto/x509" 22 | 23 | "github.com/traceabilitychain/tacchain/bccsp" 24 | "github.com/traceabilitychain/tacchain/bccsp/factory" 25 | "github.com/traceabilitychain/tacchain/bccsp/signer" 26 | ) 27 | 28 | // GeneratePrivateKey creates a private key and stores it in keystorePath 29 | func GeneratePrivateKey(keystorePath string) (bccsp.Key, 30 | crypto.Signer, error) { 31 | 32 | var err error 33 | var priv bccsp.Key 34 | var s crypto.Signer 35 | 36 | opts := &factory.FactoryOpts{ 37 | ProviderName: "SW", 38 | SwOpts: &factory.SwOpts{ 39 | HashFamily: "SHA2", 40 | SecLevel: 256, 41 | 42 | FileKeystore: &factory.FileKeystoreOpts{ 43 | KeyStorePath: keystorePath, 44 | }, 45 | }, 46 | } 47 | csp, err := factory.GetBCCSPFromOpts(opts) 48 | if err == nil { 49 | // generate a key 50 | priv, err = csp.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false}) 51 | if err == nil { 52 | // create a crypto.Signer 53 | s, err = signer.New(csp, priv) 54 | } 55 | } 56 | return priv, s, err 57 | } 58 | 59 | func GetECPublicKey(priv bccsp.Key) (*ecdsa.PublicKey, error) { 60 | 61 | // get the public key 62 | pubKey, err := priv.PublicKey() 63 | if err != nil { 64 | return nil, err 65 | } 66 | // marshal to bytes 67 | pubKeyBytes, err := pubKey.Bytes() 68 | if err != nil { 69 | return nil, err 70 | } 71 | // unmarshal using pkix 72 | ecPubKey, err := x509.ParsePKIXPublicKey(pubKeyBytes) 73 | if err != nil { 74 | return nil, err 75 | } 76 | return ecPubKey.(*ecdsa.PublicKey), nil 77 | } 78 | -------------------------------------------------------------------------------- /common/tools/cryptogen/metadata/metadata.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package metadata 8 | 9 | import ( 10 | "fmt" 11 | "runtime" 12 | ) 13 | 14 | // package-scoped variables 15 | 16 | // Package version 17 | var Version string 18 | 19 | // package-scoped constants 20 | 21 | // Program name 22 | const ProgramName = "cryptogen" 23 | 24 | func GetVersionInfo() string { 25 | if Version == "" { 26 | Version = "development build" 27 | } 28 | 29 | return fmt.Sprintf("%s:\n Version: %s\n Go version: %s\n OS/Arch: %s", 30 | ProgramName, Version, runtime.Version(), 31 | fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)) 32 | } 33 | -------------------------------------------------------------------------------- /common/tools/cryptogen/metadata/metadata_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package metadata_test 8 | 9 | import ( 10 | "fmt" 11 | "runtime" 12 | "testing" 13 | 14 | "github.com/traceabilitychain/tacchain/common/tools/cryptogen/metadata" 15 | "github.com/stretchr/testify/assert" 16 | ) 17 | 18 | func TestGetVersionInfo(t *testing.T) { 19 | testVersion := "TestVersion" 20 | metadata.Version = testVersion 21 | 22 | expected := fmt.Sprintf("%s:\n Version: %s\n Go version: %s\n OS/Arch: %s", 23 | metadata.ProgramName, testVersion, runtime.Version(), 24 | fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)) 25 | assert.Equal(t, expected, metadata.GetVersionInfo()) 26 | } 27 | -------------------------------------------------------------------------------- /common/tools/protolator/blackbox_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package protolator_test 18 | 19 | import ( 20 | "bytes" 21 | "testing" 22 | 23 | genesisconfig "github.com/traceabilitychain/tacchain/common/configtx/tool/localconfig" 24 | "github.com/traceabilitychain/tacchain/common/configtx/tool/provisional" 25 | . "github.com/traceabilitychain/tacchain/common/tools/protolator" 26 | 27 | "github.com/golang/protobuf/proto" 28 | "github.com/stretchr/testify/assert" 29 | ) 30 | 31 | func bidirectionalMarshal(t *testing.T, doc proto.Message) { 32 | var buffer bytes.Buffer 33 | 34 | assert.NoError(t, DeepMarshalJSON(&buffer, doc)) 35 | 36 | newRoot := proto.Clone(doc) 37 | newRoot.Reset() 38 | assert.NoError(t, DeepUnmarshalJSON(bytes.NewReader(buffer.Bytes()), newRoot)) 39 | 40 | // Note, we cannot do an equality check between newRoot and sampleDoc 41 | // because of the nondeterministic nature of binary proto marshaling 42 | // So instead we re-marshal to JSON which is a deterministic marshaling 43 | // and compare equality there instead 44 | 45 | //t.Log(doc) 46 | //t.Log(newRoot) 47 | 48 | var remarshaled bytes.Buffer 49 | assert.NoError(t, DeepMarshalJSON(&remarshaled, newRoot)) 50 | assert.Equal(t, string(buffer.Bytes()), string(remarshaled.Bytes())) 51 | //t.Log(string(buffer.Bytes())) 52 | //t.Log(string(remarshaled.Bytes())) 53 | } 54 | 55 | func TestConfigUpdate(t *testing.T) { 56 | p := provisional.New(genesisconfig.Load(genesisconfig.SampleSingleMSPSoloProfile)) 57 | ct := p.ChannelTemplate() 58 | cue, err := ct.Envelope("Foo") 59 | assert.NoError(t, err) 60 | 61 | bidirectionalMarshal(t, cue) 62 | } 63 | 64 | func TestGenesisBlock(t *testing.T) { 65 | p := provisional.New(genesisconfig.Load(genesisconfig.SampleSingleMSPSoloProfile)) 66 | gb := p.GenesisBlockForChannel("foo") 67 | 68 | bidirectionalMarshal(t, gb) 69 | 70 | } 71 | -------------------------------------------------------------------------------- /common/tools/protolator/testprotos/sample.proto: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2017 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | syntax = "proto3"; 18 | 19 | option go_package = "github.com/traceabilitychain/tacchain/common/tools/protolator/testprotos"; 20 | 21 | package testprotos; 22 | 23 | // SimpleMsg is designed to test that all three types of message fields, plain, map, 24 | // and slice are handled by the protolator tool 25 | message SimpleMsg { 26 | string plain_field = 1; 27 | map map_field = 2; 28 | repeated string slice_field = 3; 29 | } 30 | 31 | // NestedMsg is designed to test the nested message component 32 | message NestedMsg { 33 | SimpleMsg plain_nested_field = 1; 34 | map map_nested_field = 2; 35 | repeated SimpleMsg slice_nested_field = 3; 36 | } 37 | 38 | // StaticallyOpaqueMsg is designed to test the statically opaque message component 39 | // All fields are statically marshaled to the NestedMsg type 40 | message StaticallyOpaqueMsg { 41 | bytes plain_opaque_field = 1; 42 | map map_opaque_field = 2; 43 | repeated bytes slice_opaque_field = 3; 44 | } 45 | 46 | // VariablyOpaqueMsg is designed to test the staticaly opaque message component 47 | // The opaque type is determined by opaque_type 48 | message VariablyOpaqueMsg { 49 | string opaque_type = 1; 50 | bytes plain_opaque_field = 2; 51 | map map_opaque_field = 3; 52 | repeated bytes slice_opaque_field = 4; 53 | } 54 | 55 | // DynamicMsg is designed to test the dynamic message component 56 | // The dynamic wrapper applied to ContextlessMsg is determined by 57 | // dynamic_type 58 | message DynamicMsg { 59 | string dynamic_type = 1; 60 | ContextlessMsg plain_dynamic_field = 2; 61 | map map_dynamic_field = 3; 62 | repeated ContextlessMsg slice_dynamic_field = 4; 63 | } 64 | 65 | // ContextlessMsg is designed to carry a message of completely arbitrary type 66 | // Because there is no context for the type embedded in the message, the opaque 67 | // type must be dynamically added at runtime 68 | message ContextlessMsg { 69 | bytes opaque_field = 1; 70 | } 71 | -------------------------------------------------------------------------------- /core/wallet/wallet.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright TraceabilityChain Corp. 2018 All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package wallet 8 | 9 | import ( 10 | "encoding/hex" 11 | "math/big" 12 | "strings" 13 | ) 14 | 15 | const ( 16 | HashLength = 32 17 | AddressLength = 20 18 | HashStringLength = 64 19 | AddressStringLength = 41 20 | PriKeyLength = 32 21 | PriKeyStringLength = 64 22 | ADDRESS_PREFIX = "t" 23 | WALLET_NAMESPACE = "tab" 24 | MAIN_BALANCE_NAME = "TAB" 25 | ) 26 | 27 | type Hash [HashLength]byte 28 | type Address [AddressLength]byte 29 | 30 | var TacMinimumFee *big.Int 31 | 32 | type Account struct { 33 | Balance map[string]*big.Int `json:"balance"` 34 | Counter uint64 `json:"counter"` 35 | } 36 | 37 | type TxData struct { 38 | Sender *Address `json:"from"` 39 | Recipient *Address `json:"to"` 40 | BalanceType string `json:"balanceType"` 41 | Amount *big.Int `json:"amount"` 42 | } 43 | 44 | func (a *Address) SetBytes(b []byte) { 45 | if len(b) > AddressLength { 46 | b = b[len(b)-AddressLength:] 47 | } 48 | copy(a[AddressLength-len(b):], b) 49 | } 50 | 51 | func BytesToAddress(b []byte) *Address { 52 | a := Address{} 53 | a.SetBytes(b) 54 | return &a 55 | } 56 | 57 | func (a *Address) ToBytes() []byte { 58 | return a[:] 59 | } 60 | 61 | func StringToAddress(b string) *Address { 62 | if !strings.HasPrefix(b, ADDRESS_PREFIX) { 63 | return nil 64 | } 65 | c := strings.TrimLeft(b, ADDRESS_PREFIX) 66 | a := Address{} 67 | bytes, err := hex.DecodeString(strings.ToLower(c)) 68 | if err != nil { 69 | return nil 70 | } 71 | a.SetBytes(bytes) 72 | return &a 73 | } 74 | 75 | func (a *Address) ToString() string { 76 | return string(ADDRESS_PREFIX + hex.EncodeToString(a[:])) 77 | } 78 | 79 | func (a *Hash) SetBytes(b []byte) { 80 | if len(b) > HashLength { 81 | b = b[len(b)-HashLength:] 82 | } 83 | copy(a[HashLength-len(b):], b) 84 | } 85 | 86 | func BytesToHash(b []byte) *Hash { 87 | a := Hash{} 88 | a.SetBytes(b) 89 | return &a 90 | } 91 | 92 | func (a *Hash) ToBytes() []byte { 93 | return a[:] 94 | } 95 | 96 | func SignatureStringToBytes(sig string) ([]byte, error) { 97 | return hex.DecodeString(sig) 98 | } 99 | 100 | func SignatureBytesToString(sig []byte) string { 101 | return hex.EncodeToString(sig) 102 | } 103 | -------------------------------------------------------------------------------- /docs/images/transet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TraceabilityChain/TAC/3da98e9661457977f5b992e7a5a12e4d26133ca0/docs/images/transet.png -------------------------------------------------------------------------------- /docs/usecases.md: -------------------------------------------------------------------------------- 1 | ## Use Cases 2 | 3 | The service scope of Tac consortium blockchain involves an independent blockchain at the bottom, transaction platforms for cultural assets, and the following distributed economic ecology. 4 | 5 | Today's Creative Industry, especially IP and content ecosphere, is faced with the following problems because of backward infrastructure, serious information asymmetry and centralized governance thinking. 6 | 7 | * Unclear ownership results in ineffective incubation of many excellent IPs and content as well as frequent disputes; 8 | 9 | * The lack of data authenticity leads to unfair distribution of interests, which greatly frustrates the creative enthusiasm of many high-quality content creators; 10 | 11 | * The liquidation threshold is high, and the creators need earlier and more direct content liquidation channels; 12 | 13 | * Centralized content management mechanism makes major platforms prioritize mature content creators in terms of resources distribution, and the lack of care and attention to emerging creators leads to the waste of many high-quality content and IP; 14 | 15 | * The industry ecology and infrastructure are not sound. In addition to a few head resources, many high-quality creative cultural resources in the upper and middle ends can only be transformed once or initially, and their potential is not fully exploited. 16 | 17 | The birth of Tac consortium blockchain is expected to solve these problems thoroughly, thus leading the Creative Industry into a whole new era. 18 | -------------------------------------------------------------------------------- /events/consumer/adapter.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package consumer 18 | 19 | import ( 20 | "github.com/traceabilitychain/tacchain/protos/peer" 21 | ) 22 | 23 | //EventAdapter is the interface by which a tacchain event client registers interested events and 24 | //receives messages from the tacchain event Server 25 | type EventAdapter interface { 26 | GetInterestedEvents() ([]*peer.Interest, error) 27 | Recv(msg *peer.Event) (bool, error) 28 | Disconnected(err error) 29 | } 30 | -------------------------------------------------------------------------------- /events/producer/producer.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package producer 18 | 19 | import ( 20 | "fmt" 21 | "io" 22 | "time" 23 | 24 | "github.com/traceabilitychain/tacchain/common/flogging" 25 | pb "github.com/traceabilitychain/tacchain/protos/peer" 26 | ) 27 | 28 | var logger = flogging.MustGetLogger("eventhub_producer") 29 | 30 | // EventsServer implementation of the Peer service 31 | type EventsServer struct { 32 | } 33 | 34 | //singleton - if we want to create multiple servers, we need to subsume events.gEventConsumers into EventsServer 35 | var globalEventsServer *EventsServer 36 | 37 | // NewEventsServer returns a EventsServer 38 | func NewEventsServer(bufferSize uint, timeout time.Duration) *EventsServer { 39 | if globalEventsServer != nil { 40 | panic("Cannot create multiple event hub servers") 41 | } 42 | globalEventsServer = new(EventsServer) 43 | initializeEvents(bufferSize, timeout) 44 | //initializeCCEventProcessor(bufferSize, timeout) 45 | return globalEventsServer 46 | } 47 | 48 | // Chat implementation of the Chat bidi streaming RPC function 49 | func (p *EventsServer) Chat(stream pb.Events_ChatServer) error { 50 | handler, err := newEventHandler(stream) 51 | if err != nil { 52 | return fmt.Errorf("error creating handler during handleChat initiation: %s", err) 53 | } 54 | defer handler.Stop() 55 | for { 56 | in, err := stream.Recv() 57 | if err == io.EOF { 58 | logger.Debug("Received EOF, ending Chat") 59 | return nil 60 | } 61 | if err != nil { 62 | e := fmt.Errorf("error during Chat, stopping handler: %s", err) 63 | logger.Error(e.Error()) 64 | return e 65 | } 66 | err = handler.HandleMessage(in) 67 | if err != nil { 68 | logger.Errorf("Error handling message: %s", err) 69 | return err 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /events/producer/register_internal_events.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | //All changes for handling internal events should be in this file 18 | //Step 1 - add the event type name to the const 19 | //Step 2 - add a case statement to getMessageType 20 | //Step 3 - add an AddEventType call to addInternalEventTypes 21 | 22 | package producer 23 | 24 | import ( 25 | pb "github.com/traceabilitychain/tacchain/protos/peer" 26 | ) 27 | 28 | //----Event Types ----- 29 | /*const ( 30 | RegisterType = "register" 31 | RejectionType = "rejection" 32 | BlockType = "block" 33 | )*/ 34 | 35 | func getMessageType(e *pb.Event) pb.EventType { 36 | switch e.Event.(type) { 37 | case *pb.Event_Register: 38 | return pb.EventType_REGISTER 39 | case *pb.Event_Block: 40 | return pb.EventType_BLOCK 41 | case *pb.Event_ChaincodeEvent: 42 | return pb.EventType_CHAINCODE 43 | case *pb.Event_Rejection: 44 | return pb.EventType_REJECTION 45 | default: 46 | return -1 47 | } 48 | } 49 | 50 | //should be called at init time to register supported internal events 51 | func addInternalEventTypes() { 52 | AddEventType(pb.EventType_BLOCK) 53 | AddEventType(pb.EventType_CHAINCODE) 54 | AddEventType(pb.EventType_REJECTION) 55 | AddEventType(pb.EventType_REGISTER) 56 | } 57 | -------------------------------------------------------------------------------- /examples/cli_test/.env: -------------------------------------------------------------------------------- 1 | COMPOSE_PROJECT_NAME=net -------------------------------------------------------------------------------- /examples/cli_test/base.yaml: -------------------------------------------------------------------------------- 1 | # Copyright TraceabilityChain Corp. 2018 All Rights Reserved. 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | 6 | version: '2' 7 | services: 8 | peer-base: 9 | image: traceabilitychain/tacchain-peer 10 | environment: 11 | - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock 12 | - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_default 13 | - CORE_LOGGING_LEVEL=DEBUG 14 | - CORE_PEER_GOSSIP_USELEADERELECTION=true 15 | - CORE_PEER_GOSSIP_ORGLEADER=false 16 | - CORE_PEER_GOSSIP_SKIPHANDSHAKE=true 17 | - CORE_PEER_MSPCONFIGPATH=/etc/tacchain/crypto/peer/msp 18 | - CORE_PEER_TLS_ENABLED=true 19 | - CORE_PEER_TLS_KEY_FILE=/etc/tacchain/crypto/peer/tls/server.key 20 | - CORE_PEER_TLS_CERT_FILE=/etc/tacchain/crypto/peer/tls/server.crt 21 | - CORE_PEER_TLS_ROOTCERT_FILE=/etc/tacchain/crypto/peer/tls/ca.crt 22 | - GODEBUG=netdns=go 23 | working_dir: /opt/gopath/src/github.com/traceabilitychain/tacchain/peer 24 | command: peer node start 25 | volumes: 26 | - /var/run/:/host/var/run/ 27 | -------------------------------------------------------------------------------- /examples/cli_test/channel/genesis.block: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TraceabilityChain/TAC/3da98e9661457977f5b992e7a5a12e4d26133ca0/examples/cli_test/channel/genesis.block -------------------------------------------------------------------------------- /examples/cli_test/channel/mychannel.tx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TraceabilityChain/TAC/3da98e9661457977f5b992e7a5a12e4d26133ca0/examples/cli_test/channel/mychannel.tx -------------------------------------------------------------------------------- /examples/cli_test/clean-environment.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright TraceabilityChain Corp. 2018 All Rights Reserved 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | 8 | set -e 9 | 10 | # Shut down the Docker containers for the system tests. 11 | docker-compose -f docker-compose.yml stop && docker-compose -f docker-compose.yml down 12 | 13 | # remove chaincode docker images 14 | docker rmi $(docker images dev-* -q) 15 | 16 | # Your system is now clean 17 | -------------------------------------------------------------------------------- /examples/xc/docker-qtum/test/XCPlugin/send/setAdmin.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | source p_init.sh 4 | 5 | qcli sendtocontract $XCPluginHexAddress `solar encode contracts/XCPlugin.sol setAdmin '["'$XCPluginHexOwner'"]'` 0 6000000 0.0000004 $XCPluginOwner -------------------------------------------------------------------------------- /examples/xc/docker-qtum/test/XCPlugin/send/setPlatformName.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | source p_init.sh 4 | 5 | qcli sendtocontract $XCPluginHexAddress `solar encode contracts/XCPlugin.sol setPlatformName '["7174756d00000000000000000000000000000000000000000000000000000000"]'` 0 6000000 0.0000004 $XCPluginOwner -------------------------------------------------------------------------------- /examples/xc/docker-qtum/test/XCPlugin/send/setWeight.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | source p_init.sh 4 | 5 | qcli sendtocontract $XCPluginHexAddress `solar encode contracts/XCPlugin.sol setWeight '["4100000000000000000000000000000000000000000000000000000000000000",3]'` 0 6000000 0.0000004 $XCPluginOwner -------------------------------------------------------------------------------- /examples/xc/docker-qtum/test/XCPlugin/send/start.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | source p_init.sh 4 | 5 | qcli sendtocontract $XCPluginHexAddress `solar encode contracts/XCPlugin.sol start` 0 6000000 0.0000004 $XCPluginOwner 6 | -------------------------------------------------------------------------------- /examples/xc/docker-qtum/test/XCPlugin/send/stop.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | source p_init.sh 4 | 5 | qcli sendtocontract $XCPluginHexAddress `solar encode contracts/XCPlugin.sol stop` 0 6000000 0.0000004 $XCPluginOwner -------------------------------------------------------------------------------- /examples/xc/docker-qtum/test/XCPlugin/send/voter.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | source p_init.sh 4 | 5 | qcli sendtocontract $XCPluginHexAddress `solar encode contracts/XCPlugin.sol voter '["4100000000000000000000000000000000000000000000000000000000000000","d6b39eb631df8ee60e46a576231ccf1fcd204a5e","d6b39eb631df8ee60e46a576231ccf1fcd204a5e",1000,"4200000000000000000000000000000000000000000000000000000000000000","4100000000000000000000000000000000000000000000000000000000000000","4100000000000000000000000000000000000000000000000000000000000000",27]'` 0 6000000 0.0000004 $XCPluginOwner 6 | # voter(bytes32,address,address,uint256,bytes32,bytes32,bytes32,uint8) --------------------------------------------------------------------------------