当前位置: 首页>>代码示例>>Golang>>正文


Golang util.ComputeCryptoHash函数代码示例

本文整理汇总了Golang中github.com/hyperledger/fabric/core/util.ComputeCryptoHash函数的典型用法代码示例。如果您正苦于以下问题:Golang ComputeCryptoHash函数的具体用法?Golang ComputeCryptoHash怎么用?Golang ComputeCryptoHash使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ComputeCryptoHash函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: authorize

func (sc *systemChain) authorize(configEnvelope *cb.ConfigurationEnvelope) cb.Status {
	creationConfigItem := &cb.ConfigurationItem{}
	err := proto.Unmarshal(configEnvelope.Items[0].ConfigurationItem, creationConfigItem)
	if err != nil {
		logger.Debugf("Failing to validate chain creation because of unmarshaling error: %s", err)
		return cb.Status_BAD_REQUEST
	}

	if creationConfigItem.Key != utils.CreationPolicyKey {
		logger.Debugf("Failing to validate chain creation because first configuration item was not the CreationPolicy")
		return cb.Status_BAD_REQUEST
	}

	creationPolicy := &ab.CreationPolicy{}
	err = proto.Unmarshal(creationConfigItem.Value, creationPolicy)
	if err != nil {
		logger.Debugf("Failing to validate chain creation because first configuration item could not unmarshal to a CreationPolicy: %s", err)
		return cb.Status_BAD_REQUEST
	}

	ok := false
	for _, chainCreatorPolicy := range sc.support.SharedConfig().ChainCreators() {
		if chainCreatorPolicy == creationPolicy.Policy {
			ok = true
			break
		}
	}

	if !ok {
		logger.Debugf("Failed to validate chain creation because chain creation policy is not authorized for chain creation")
		return cb.Status_FORBIDDEN
	}

	policy, ok := sc.support.PolicyManager().GetPolicy(creationPolicy.Policy)
	if !ok {
		logger.Debugf("Failed to get policy for chain creation despite it being listed as an authorized policy")
		return cb.Status_INTERNAL_SERVER_ERROR
	}

	// XXX actually do policy signature validation
	_ = policy

	var remainingBytes []byte
	for i, item := range configEnvelope.Items {
		if i == 0 {
			// Do not include the creation policy
			continue
		}
		remainingBytes = append(remainingBytes, item.ConfigurationItem...)
	}

	configHash := util.ComputeCryptoHash(remainingBytes)

	if !bytes.Equal(configHash, creationPolicy.Digest) {
		logger.Debugf("Validly signed chain creation did not contain correct digest for remaining configuration %x vs. %x", configHash, creationPolicy.Digest)
		return cb.Status_BAD_REQUEST
	}

	return cb.Status_SUCCESS
}
开发者ID:hyperledger,项目名称:fabric,代码行数:60,代码来源:systemchain.go

示例2: TestHashContentChange

// TestHashContentChange changes a random byte in a content and checks for hash change
func TestHashContentChange(t *testing.T) {
	b := []byte("firstcontent")
	hash := util.ComputeCryptoHash(b)

	b2 := []byte("To be, or not to be- that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune Or to take arms against a sea of troubles, And by opposing end them. To die- to sleep- No more; and by a sleep to say we end The heartache, and the thousand natural shocks That flesh is heir to. 'Tis a consummation Devoutly to be wish'd.")

	h1 := computeHash(b2, hash)

	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	randIndex := (int(r.Uint32())) % len(b2)

	randByte := byte((int(r.Uint32())) % 128)

	//make sure the two bytes are different
	for {
		if randByte != b2[randIndex] {
			break
		}

		randByte = byte((int(r.Uint32())) % 128)
	}

	//change a random byte
	b2[randIndex] = randByte

	//this is the core hash func under test
	h2 := computeHash(b2, hash)

	//the two hashes should be different
	if bytes.Compare(h1, h2) == 0 {
		t.Fail()
		t.Logf("Hash expected to be different but is same")
	}
}
开发者ID:C0rWin,项目名称:fabric,代码行数:35,代码来源:hash_test.go

示例3: computeCryptoHash

func (trieNode *trieNode) computeCryptoHash() []byte {
	stateTrieLogger.Debug("Enter computeCryptoHash() for trieNode [%s]", trieNode)
	var cryptoHashContent []byte
	if trieNode.containsValue() {
		stateTrieLogger.Debug("Adding value to hash computation for trieNode [%s]", trieNode)
		key := trieNode.trieKey.getEncodedBytes()
		cryptoHashContent = append(cryptoHashContent, proto.EncodeVarint(uint64(len(key)))...)
		cryptoHashContent = append(cryptoHashContent, key...)
		cryptoHashContent = append(cryptoHashContent, trieNode.value...)
	}

	sortedChildrenIndexes := trieNode.getSortedChildrenIndex()
	for _, index := range sortedChildrenIndexes {
		childCryptoHash := trieNode.childrenCryptoHashes[index]
		stateTrieLogger.Debug("Adding hash [%#v] for child number [%d] to hash computation for trieNode [%s]", childCryptoHash, index, trieNode)
		cryptoHashContent = append(cryptoHashContent, childCryptoHash...)
	}

	if cryptoHashContent == nil {
		// node has no associated value and no associated children.
		stateTrieLogger.Debug("Returning nil as hash for trieNode = [%s]. Also, marking this key for deletion.", trieNode)
		trieNode.markedForDeletion = true
		return nil
	}

	if !trieNode.containsValue() && trieNode.getNumChildren() == 1 {
		// node has no associated value and has a single child. Propagate the child hash up
		stateTrieLogger.Debug("Returning hash as of a single child for trieKey = [%s]", trieNode.trieKey)
		return cryptoHashContent
	}

	stateTrieLogger.Debug("Recomputing hash for trieKey = [%s]", trieNode)
	return util.ComputeCryptoHash(cryptoHashContent)
}
开发者ID:RicHernandez2,项目名称:fabric,代码行数:34,代码来源:trie_node.go

示例4: TestGoodProposal

func TestGoodProposal(t *testing.T) {
	newChainID := "NewChainID"

	mcc := newMockChainCreator()
	mcc.ms.msc.chainCreators = []string{provisional.AcceptAllPolicyKey}
	mcc.ms.mpm.mp = &mockPolicy{}

	chainCreateTx := &cb.ConfigurationItem{
		Header: &cb.ChainHeader{
			ChainID: newChainID,
			Type:    int32(cb.HeaderType_CONFIGURATION_ITEM),
		},
		Key:  utils.CreationPolicyKey,
		Type: cb.ConfigurationItem_Orderer,
		Value: utils.MarshalOrPanic(&ab.CreationPolicy{
			Policy: provisional.AcceptAllPolicyKey,
			Digest: coreutil.ComputeCryptoHash([]byte{}),
		}),
	}
	ingressTx := makeConfigTxWithItems(newChainID, chainCreateTx)
	status := mcc.sysChain.proposeChain(ingressTx)
	if status != cb.Status_SUCCESS {
		t.Fatalf("Should have successfully proposed chain")
	}

	expected := 1
	if len(mcc.ms.queue) != expected {
		t.Fatalf("Expected %d creation txs in the chain, but found %d", expected, len(mcc.ms.queue))
	}

	wrapped := mcc.ms.queue[0]
	payload := utils.UnmarshalPayloadOrPanic(wrapped.Payload)
	if payload.Header.ChainHeader.Type != int32(cb.HeaderType_ORDERER_TRANSACTION) {
		t.Fatalf("Wrapped transaction should be of type ORDERER_TRANSACTION")
	}
	envelope := utils.UnmarshalEnvelopeOrPanic(payload.Data)
	if !reflect.DeepEqual(envelope, ingressTx) {
		t.Fatalf("Received different configtx than ingressed into the system")
	}

	sysFilter := newSystemChainFilter(mcc)
	action, committer := sysFilter.Apply(wrapped)

	if action != filter.Accept {
		t.Fatalf("Should have accepted the transaction, as it was already validated")
	}

	if !committer.Isolated() {
		t.Fatalf("Chain creation transactions should be isolated on commit")
	}

	committer.Commit()
	if len(mcc.newChains) != 1 {
		t.Fatalf("Proposal should only have created 1 new chain")
	}

	if !reflect.DeepEqual(mcc.newChains[0], ingressTx) {
		t.Fatalf("New chain should have been created with ingressTx")
	}
}
开发者ID:hyperledger,项目名称:fabric,代码行数:60,代码来源:systemchain_test.go

示例5: TestHashSameRemoteRepo

func TestHashSameRemoteRepo(t *testing.T) {
	b := []byte("firstcontent")
	hash := util.ComputeCryptoHash(b)

	srcPath1, err := getCodeFromHTTP("https://github.com/xspeedcruiser/javachaincodemvn")
	srcPath2, err := getCodeFromHTTP("https://github.com/xspeedcruiser/javachaincodemvn")

	if err != nil {
		t.Logf("Error getting code from remote repo %s", err)
		t.Fail()
	}

	defer func() {
		os.RemoveAll(srcPath1)
	}()
	defer func() {
		os.RemoveAll(srcPath2)
	}()
	hash1, err := hashFilesInDir(srcPath1, srcPath1, hash, nil)
	if err != nil {
		t.Logf("Error getting code %s", err)
		t.Fail()
	}
	hash2, err := hashFilesInDir(srcPath2, srcPath2, hash, nil)
	if err != nil {
		t.Logf("Error getting code %s", err)
		t.Fail()
	}
	if bytes.Compare(hash1, hash2) != 0 {
		t.Logf("Hash should be same across multiple downloads")
		t.Fail()
	}
}
开发者ID:yoshiharay,项目名称:fabric,代码行数:33,代码来源:hash_test.go

示例6: Hash

func (b *BlockData) Hash() []byte {
	data, err := proto.Marshal(b) // XXX this is wrong, protobuf is not the right mechanism to serialize for a hash, AND, it is not a MerkleTree hash
	if err != nil {
		panic("This should never fail and is generally irrecoverable")
	}

	return util.ComputeCryptoHash(data)
}
开发者ID:hyperledger,项目名称:fabric,代码行数:8,代码来源:block.go

示例7: computeCryptoHash

func (c *bucketHashCalculator) computeCryptoHash() []byte {
	if c.currentChaincodeID != "" {
		c.appendCurrentChaincodeData()
		c.currentChaincodeID = ""
		c.dataNodes = nil
	}
	logger.Debug("Hashable content for bucket [%s]: length=%d, contentInStringForm=[%s]", c.bucketKey, len(c.hashingData), string(c.hashingData))
	if util.IsNil(c.hashingData) {
		return nil
	}
	return openchainUtil.ComputeCryptoHash(c.hashingData)
}
开发者ID:RicHernandez2,项目名称:fabric,代码行数:12,代码来源:bucket_hash.go

示例8: expectedCryptoHashForTest

func expectedCryptoHashForTest(key *trieKey, value []byte, childrenHashes ...[]byte) []byte {
	expectedHash := []byte{}
	if key != nil {
		keyBytes := key.getEncodedBytes()
		expectedHash = append(expectedHash, proto.EncodeVarint(uint64(len(keyBytes)))...)
		expectedHash = append(expectedHash, keyBytes...)
		expectedHash = append(expectedHash, value...)
	}
	for _, b := range childrenHashes {
		expectedHash = append(expectedHash, b...)
	}
	return util.ComputeCryptoHash(expectedHash)
}
开发者ID:C0rWin,项目名称:fabric,代码行数:13,代码来源:pkg_test.go

示例9: GetName

//GetName returns canonical chaincode name based on chain name
func (ccid *CCID) GetName() string {
	if ccid.ChaincodeSpec == nil {
		panic("nil chaincode spec")
	}

	//this better be chainless system chaincode!
	if ccid.ChainID != "" {
		hash := util.ComputeCryptoHash([]byte(ccid.ChainID))
		hexstr := hex.EncodeToString(hash[:])
		return ccid.ChaincodeSpec.ChaincodeID.Name + "-" + hexstr
	}

	return ccid.ChaincodeSpec.ChaincodeID.Name
}
开发者ID:hyperledger,项目名称:fabric,代码行数:15,代码来源:ccintf.go

示例10: hash

func hash(msg interface{}) string {
	var raw []byte
	switch converted := msg.(type) {
	case *Request:
		raw, _ = proto.Marshal(converted)
	case *RequestBatch:
		raw, _ = proto.Marshal(converted)
	default:
		logger.Error("Asked to hash non-supported message type, ignoring")
		return ""
	}
	return base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(raw))

}
开发者ID:srderson,项目名称:fabric,代码行数:14,代码来源:util.go

示例11: computeHash

//core hash computation factored out for testing
func computeHash(contents []byte, hash []byte) []byte {
	newSlice := make([]byte, len(hash)+len(contents))

	//copy the contents
	copy(newSlice[0:len(contents)], contents[:])

	//add the previous hash
	copy(newSlice[len(contents):], hash[:])

	//compute new hash
	hash = util.ComputeCryptoHash(newSlice)

	return hash
}
开发者ID:hyperledger,项目名称:fabric,代码行数:15,代码来源:hash.go

示例12: TestHashOrderChange

// TestHashOrderChange changes a order of hash computation over a list of lines and checks for hash change
func TestHashOrderChange(t *testing.T) {
	b := []byte("firstcontent")
	hash := util.ComputeCryptoHash(b)

	b2 := [][]byte{[]byte("To be, or not to be- that is the question:"),
		[]byte("Whether 'tis nobler in the mind to suffer"),
		[]byte("The slings and arrows of outrageous fortune"),
		[]byte("Or to take arms against a sea of troubles,"),
		[]byte("And by opposing end them."),
		[]byte("To die- to sleep- No more; and by a sleep to say we end"),
		[]byte("The heartache, and the thousand natural shocks"),
		[]byte("That flesh is heir to."),
		[]byte("'Tis a consummation Devoutly to be wish'd.")}
	h1 := hash

	for _, l := range b2 {
		h1 = computeHash(l, h1)
	}

	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	randIndex1 := (int(r.Uint32())) % len(b2)
	randIndex2 := (int(r.Uint32())) % len(b2)

	//make sure the two indeces are different
	for {
		if randIndex2 != randIndex1 {
			break
		}

		randIndex2 = (int(r.Uint32())) % len(b2)
	}

	//switch two arbitrary lines
	tmp := b2[randIndex2]
	b2[randIndex2] = b2[randIndex1]
	b2[randIndex1] = tmp

	h2 := hash
	for _, l := range b2 {
		h2 = computeHash(l, hash)
	}

	//hash should be different
	if bytes.Compare(h1, h2) == 0 {
		t.Fail()
		t.Logf("Hash expected to be different but is same")
	}
}
开发者ID:C0rWin,项目名称:fabric,代码行数:49,代码来源:hash_test.go

示例13: BenchmarkCryptoHash

func BenchmarkCryptoHash(b *testing.B) {
	flags := flag.NewFlagSet("testParams", flag.ExitOnError)
	numBytesPointer := flags.Int("NumBytes", -1, "Number of Bytes")
	flags.Parse(testParams)
	numBytes := *numBytesPointer
	if numBytes == -1 {
		b.Fatal("Missing value for parameter NumBytes")
	}

	randomBytes := testutil.ConstructRandomBytes(b, numBytes)
	//b.Logf("byte size=%d, b.N=%d", len(randomBytes), b.N)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		util.ComputeCryptoHash(randomBytes)
	}
}
开发者ID:C0rWin,项目名称:fabric,代码行数:16,代码来源:perf_test.go

示例14: TestHashOverLocalDir

func TestHashOverLocalDir(t *testing.T) {
	b := []byte("firstcontent")
	hash := util.ComputeCryptoHash(b)

	hash, err := hashFilesInDir(".", "../golang/hashtestfiles", hash, nil)

	if err != nil {
		t.Fail()
		t.Logf("error : %s", err)
	}

	expectedHash := "7b3b2193bed2bd7c19300aa5d6d7f6bb4d61602e4978a78bc08028379cb5cf0ed877bd9db3e990230e8bf6c974edd765f3027f061fd8657d30fc858a676a6f4a"

	computedHash := hex.EncodeToString(hash[:])

	if expectedHash != computedHash {
		t.Fail()
		t.Logf("Hash expected to be unchanged")
	}
}
开发者ID:yoshiharay,项目名称:fabric,代码行数:20,代码来源:hash_test.go

示例15: GetHash

// GetHash returns the hash of this block.
func (block *Block) GetHash() ([]byte, error) {

	// copy the block and remove the non-hash data
	blockBytes, err := block.Bytes()
	if err != nil {
		return nil, fmt.Errorf("Could not calculate hash of block: %s", err)
	}
	blockCopy, err := UnmarshallBlock(blockBytes)
	if err != nil {
		return nil, fmt.Errorf("Could not calculate hash of block: %s", err)
	}
	blockCopy.NonHashData = nil

	// Hash the block
	data, err := proto.Marshal(blockCopy)
	if err != nil {
		return nil, fmt.Errorf("Could not calculate hash of block: %s", err)
	}
	hash := util.ComputeCryptoHash(data)
	return hash, nil
}
开发者ID:RicHernandez2,项目名称:fabric,代码行数:22,代码来源:block.go


注:本文中的github.com/hyperledger/fabric/core/util.ComputeCryptoHash函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。