示例#1
0
func ComputeCryptoHash(content ...[]byte) []byte {
	combinedContent := []byte{}
	for _, b := range content {
		combinedContent = append(combinedContent, b...)
	}
	return util.ComputeCryptoHash(combinedContent)
}
示例#2
0
func (inst *instance) execute(payload []byte) {

	tx := &pb.Transaction{
		Payload: payload,
	}

	txs := []*pb.Transaction{tx}
	txBatchID := base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(payload))

	if err := inst.BeginTxBatch(txBatchID); err != nil {
		fmt.Printf("Failed to begin transaction %s: %v", txBatchID, err)
		return
	}

	if _, err := inst.ExecTxs(txBatchID, txs); nil != err {
		fmt.Printf("Fail to execute transaction %s: %v", txBatchID, err)
		if err := inst.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction %s: %v", txBatchID, err))
		}
		return
	}

	if _, err := inst.CommitTxBatch(txBatchID, nil); err != nil {
		fmt.Printf("Failed to commit transaction %s to the ledger: %v", txBatchID, err)
		if err = inst.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction %s: %v", txBatchID, err))
		}
		return
	}

}
示例#3
0
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)
		cryptoHashContent = append(cryptoHashContent, trieNode.trieKey.getEncodedBytes()...)
		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)
}
示例#4
0
//hashFilesInDir computes h=hash(h,file bytes) for each file in a directory
//Directory entries are traversed recursively. In the end a single
//hash value is returned for the entire directory structure
func hashFilesInDir(rootDir string, dir string, hash []byte, tw *tar.Writer) ([]byte, error) {
	//ReadDir returns sorted list of files in dir
	fis, err := ioutil.ReadDir(rootDir + "/" + dir)
	if err != nil {
		return hash, fmt.Errorf("ReadDir failed %s\n", err)
	}
	for _, fi := range fis {
		name := fmt.Sprintf("%s/%s", dir, fi.Name())
		if fi.IsDir() {
			var err error
			hash, err = hashFilesInDir(rootDir, name, hash, tw)
			if err != nil {
				return hash, err
			}
			continue
		}
		buf, err := ioutil.ReadFile(rootDir + "/" + name)
		if err != nil {
			fmt.Printf("Error reading %s\n", err)
			return hash, err
		}

		newSlice := make([]byte, len(hash)+len(buf))
		copy(newSlice[len(buf):], hash[:])
		//hash = md5.Sum(newSlice)
		hash = util.ComputeCryptoHash(newSlice)

		if tw != nil {
			if err = addFile(tw, "src/"+name, fi, buf); err != nil {
				return hash, fmt.Errorf("Error adding file to tar %s", err)
			}
		}
	}
	return hash, nil
}
示例#5
0
func (op *obcSieve) processExecute() {
	if op.currentReq != "" {
		return
	}

	primary := op.pbft.primary(op.epoch)
	exec := op.queuedExec[primary]
	delete(op.queuedExec, primary)

	if exec == nil {
		return
	}

	if !(exec.View == op.epoch && op.pbft.primary(op.epoch) == exec.ReplicaId && op.pbft.activeView) {
		logger.Debug("Invalid execute from %d", exec.ReplicaId)
		return
	}

	if exec.BlockNumber != op.blockNumber+1 {
		logger.Debug("Invalid block number in execute: expected %d, got %d",
			op.blockNumber+1, exec.BlockNumber)
		return
	}

	logger.Debug("Sieve replica %d received exec from %d, epoch=%d, blockNo=%d",
		op.id, exec.ReplicaId, exec.View, exec.BlockNumber)

	op.currentReq = base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(exec.Request))
	op.blockNumber++

	op.begin()
	tx := &pb.Transaction{}
	proto.Unmarshal(exec.Request, tx)
	op.currentTx = []*pb.Transaction{tx}
	hashes, _ := op.cpi.ExecTXs(op.currentTx)

	// for simplicity's sake, we use the pbft timer
	op.pbft.startTimer(op.pbft.requestTimeout)

	op.currentResult = hashes
	verify := &Verify{
		View:          exec.View,
		BlockNumber:   exec.BlockNumber,
		RequestDigest: op.currentReq,
		ResultDigest:  op.currentResult,
		ReplicaId:     op.id,
	}
	op.pbft.sign(verify)

	logger.Debug("Sieve replica %d sending verify blockNo=%d",
		op.id, verify.BlockNumber)
	op.broadcastMsg(&SieveMessage{&SieveMessage_Verify{verify}})
	op.recvVerify(verify)
}
示例#6
0
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)
}
示例#7
0
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)
}
示例#8
0
func (op *obcSieve) processExecute() {
	if op.currentReq != "" {
		return
	}

	primary := op.pbft.primary(op.epoch)
	exec := op.queuedExec[primary]
	delete(op.queuedExec, primary)

	if exec == nil {
		return
	}

	if !(exec.View == op.epoch && op.pbft.primary(op.epoch) == exec.ReplicaId && op.pbft.activeView) {
		logger.Debug("Invalid execute from %d", exec.ReplicaId)
		return
	}

	if exec.BlockNumber != op.blockNumber+1 {
		logger.Debug("Block block number in execute wrong: expected %d, got %d",
			op.blockNumber, exec.BlockNumber)
		return
	}

	op.currentReq = base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(exec.Request))

	logger.Debug("Sieve replica %d received exec from %d, epoch=%d, blockNo=%d from request=%s",
		op.id, exec.ReplicaId, exec.View, exec.BlockNumber, op.currentReq)

	// With the execution decoupled from the ordering, this sanity check is challenging and introduces a race
	/*
		blockchainSize, _ := op.stack.GetBlockchainSize()
		blockchainSize--
		if op.blockNumber != blockchainSize {
			logger.Critical("Sieve replica %d block number and ledger blockchain size diverged: blockNo=%d, blockchainSize=%d", op.id, op.blockNumber, blockchainSize)
			return
		}
	*/

	op.currentView = exec.View
	op.blockNumber = exec.BlockNumber

	tx := &pb.Transaction{}
	proto.Unmarshal(exec.Request, tx)

	op.executor.Execute(exec.BlockNumber, []*pb.Transaction{tx}, &ExecutionInfo{
		Validate: true,
	})

}
示例#9
0
//name could be ChaincodeID.Name or ChaincodeID.Path
func generateHashFromSignature(path string, ctor string, args []string) []byte {
	fargs := ctor
	if args != nil {
		for _, str := range args {
			fargs = fargs + str
		}
	}
	cbytes := []byte(path + fargs)

	b := make([]byte, len(cbytes))
	copy(b, cbytes)
	hash := util.ComputeCryptoHash(b)
	return hash
}
示例#10
0
func (instance *pbftCore) sign(s signable) error {
	s.setSignature(nil)
	// TODO once the crypto package is integrated
	// cryptoID, _, _ := instance.cpi.GetReplicaID()
	// s.setID(cryptoID)
	id := []byte("XXX ID")
	s.setID(id)
	raw, err := s.serialize()
	if err != nil {
		return err
	}
	// s.setSignature(instance.cpi.Sign(raw))
	s.setSignature(util.ComputeCryptoHash(append(id, raw...)))
	return nil
}
示例#11
0
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)
	}
}
示例#12
0
func (instance *pbftCore) verify(s signable) error {
	origSig := s.getSignature()
	s.setSignature(nil)
	raw, err := s.serialize()
	s.setSignature(origSig)
	if err != nil {
		return err
	}
	id := s.getID()
	// XXX check that s.Id() is a valid replica
	// instance.cpi.Verify(s.Id(), origSig, raw)
	if !reflect.DeepEqual(util.ComputeCryptoHash(append(id, raw...)), origSig) {
		return fmt.Errorf("invalid signature")
	}
	return nil
}
示例#13
0
// execute an opaque request which corresponds to an OBC Transaction
func (op *obcBatch) execute(tbRaw []byte) {
	tb := &pb.TransactionBlock{}
	err := proto.Unmarshal(tbRaw, tb)
	if err != nil {
		return
	}

	txs := tb.Transactions
	txBatchID := base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(tbRaw))

	for i, tx := range txs {
		txRaw, _ := proto.Marshal(tx)
		if err = op.validate(txRaw); err != nil {
			err = fmt.Errorf("Request in transaction %d from batch %s did not verify: %s", i, txBatchID, err)
			logger.Error(err.Error())
			return
		}
	}

	if err := op.stack.BeginTxBatch(txBatchID); err != nil {
		err = fmt.Errorf("Failed to begin transaction batch %s: %v", txBatchID, err)
		logger.Error(err.Error())
		return
	}

	if _, err := op.stack.ExecTxs(txBatchID, txs); nil != err {
		err = fmt.Errorf("Fail to execute transaction batch %s: %v", txBatchID, err)
		logger.Error(err.Error())
		if err = op.stack.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction batch %s: %v", txBatchID, err))
		}
		return
	}

	if _, err = op.stack.CommitTxBatch(txBatchID, nil); err != nil {
		err = fmt.Errorf("Failed to commit transaction batch %s to the ledger: %v", txBatchID, err)
		logger.Error(err.Error())
		if err = op.stack.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction batch %s: %v", txBatchID, err))
		}
		return
	}
}
示例#14
0
// execute an opaque request which corresponds to an OBC Transaction
func (op *obcClassic) execute(txRaw []byte) {
	if err := op.validate(txRaw); err != nil {
		err = fmt.Errorf("Request in transaction did not validate: %s", err)
		logger.Error(err.Error())
		return
	}

	tx := &pb.Transaction{}
	err := proto.Unmarshal(txRaw, tx)
	if err != nil {
		err = fmt.Errorf("Unable to unmarshal transaction: %v", err)
		logger.Error(err.Error())
		return
	}

	txs := []*pb.Transaction{tx}
	txBatchID := base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(txRaw))

	if err := op.stack.BeginTxBatch(txBatchID); err != nil {
		err = fmt.Errorf("Failed to begin transaction %s: %v", txBatchID, err)
		logger.Error(err.Error())
		return
	}

	if _, err := op.stack.ExecTxs(txBatchID, txs); nil != err {
		err = fmt.Errorf("Failed to execute transaction %s: %v", txBatchID, err)
		logger.Error(err.Error())
		if err = op.stack.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction %s: %v", txBatchID, err))
		}
		return
	}

	if _, err = op.stack.CommitTxBatch(txBatchID, nil); err != nil {
		err = fmt.Errorf("Failed to commit transaction %s to the ledger: %v", txBatchID, err)
		logger.Error(err.Error())
		if err = op.stack.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction %s: %v", txBatchID, err))
		}
		return
	}
}
示例#15
0
func computeDataNodesCryptoHash(bucketKey *bucketKey, updatedNodes dataNodes, existingNodes dataNodes) []byte {
	logger.Debug("Computing crypto-hash for bucket [%s]. numUpdatedNodes=[%d], numExistingNodes=[%d]", bucketKey, len(updatedNodes), len(existingNodes))
	hashableContent := []byte{}
	i := 0
	j := 0
	for i < len(updatedNodes) && j < len(existingNodes) {
		updatedNode := updatedNodes[i]
		existingNode := existingNodes[j]
		c := bytes.Compare(updatedNode.dataKey.compositeKey, existingNode.dataKey.compositeKey)
		var nextNode *dataNode
		switch c {
		case -1:
			nextNode = updatedNode
			i++
		case 0:
			nextNode = updatedNode
			i++
			j++
		case 1:
			nextNode = existingNode
			j++
		}
		hashableContent = addNodeData(hashableContent, nextNode)
	}

	var remainingNodes dataNodes
	if i < len(updatedNodes) {
		remainingNodes = updatedNodes[i:]
	} else if j < len(existingNodes) {
		remainingNodes = existingNodes[j:]
	}

	for _, remainingNode := range remainingNodes {
		hashableContent = addNodeData(hashableContent, remainingNode)
	}
	logger.Debug("Hashable content for bucket [%s] = [%s]", bucketKey, string(hashableContent))
	if util.IsNil(hashableContent) {
		return nil
	}
	return openchainUtil.ComputeCryptoHash(hashableContent)
}
示例#16
0
文件: block.go 项目: butine/research
// 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
}
示例#17
0
// ComputeCryptoHash computes crypto-hash for the data held
// returns nil if no data is present
func (stateDelta *StateDelta) ComputeCryptoHash() []byte {
	if stateDelta.IsEmpty() {
		return nil
	}
	var buffer bytes.Buffer
	sortedChaincodeIds := stateDelta.GetUpdatedChaincodeIds(true)
	for _, chaincodeID := range sortedChaincodeIds {
		buffer.WriteString(chaincodeID)
		chaincodeStateDelta := stateDelta.chaincodeStateDeltas[chaincodeID]
		sortedKeys := chaincodeStateDelta.getSortedKeys()
		for _, key := range sortedKeys {
			buffer.WriteString(key)
			updatedValue := chaincodeStateDelta.get(key)
			if !updatedValue.IsDelete() {
				buffer.Write(updatedValue.value)
			}
		}
	}
	hashingContent := buffer.Bytes()
	logger.Debug("computing hash on %#v", hashingContent)
	return util.ComputeCryptoHash(hashingContent)
}
示例#18
0
func (bucketNode *bucketNode) computeCryptoHash() []byte {
	cryptoHashContent := []byte{}
	numChildren := 0
	for i, childCryptoHash := range bucketNode.childrenCryptoHash {
		if util.NotNil(childCryptoHash) {
			numChildren++
			logger.Debug("Appending crypto-hash for child bucket = [%s]", bucketNode.bucketKey.getChildKey(i))
			cryptoHashContent = append(cryptoHashContent, childCryptoHash...)
		}
	}
	if numChildren == 0 {
		logger.Debug("Returning <nil> crypto-hash of bucket = [%s] - because, it has not children", bucketNode.bucketKey)
		bucketNode.markedForDeletion = true
		return nil
	}
	if numChildren == 1 {
		logger.Debug("Propagating crypto-hash of single child node for bucket = [%s]", bucketNode.bucketKey)
		return cryptoHashContent
	}
	logger.Debug("Computing crypto-hash for bucket [%s] by merging [%d] children", bucketNode.bucketKey, numChildren)
	return openchainUtil.ComputeCryptoHash(cryptoHashContent)
}
示例#19
0
// execute an opaque request which corresponds to an OBC Transaction
func (op *obcClassic) execute(txRaw []byte) {
	if err := op.verify(txRaw); err != nil {
		logger.Error("Request in transaction did not verify: %s", err)
		return
	}

	tx := &pb.Transaction{}
	err := proto.Unmarshal(txRaw, tx)
	if err != nil {
		logger.Error("Unable to unmarshal transaction: %v", err)
		return
	}

	txs := []*pb.Transaction{tx}
	txBatchID := base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(txRaw))

	if err := op.cpi.BeginTxBatch(txBatchID); err != nil {
		logger.Error("Failed to begin transaction %s: %v", txBatchID, err)
		return
	}

	_, errs := op.cpi.ExecTXs(txs)
	if errs[len(txs)] != nil {
		logger.Error("Fail to execute transaction %s: %v", txBatchID, errs)
		if err = op.cpi.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction %s: %v", txBatchID, err))
		}
		return
	}

	if err = op.cpi.CommitTxBatch(txBatchID, txs, nil); err != nil {
		logger.Error("Failed to commit transaction %s to the ledger: %v", txBatchID, err)
		if err = op.cpi.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction %s: %v", txBatchID, err))
		}
		return
	}
}
示例#20
0
func ComputeCryptoHash(content ...[]byte) []byte {
	return util.ComputeCryptoHash(AppendAll(content...))
}
示例#21
0
func hashReq(req *Request) (digest string) {
	reqRaw, _ := proto.Marshal(req)
	return base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(reqRaw))
}
示例#22
0
func (op *obcSieve) processExecute() {
	if op.pbft.sts.InProgress() {
		return
	}

	if op.currentReq != "" {
		return
	}

	primary := op.pbft.primary(op.epoch)
	exec := op.queuedExec[primary]
	delete(op.queuedExec, primary)

	if exec == nil {
		return
	}

	if !(exec.View == op.epoch && op.pbft.primary(op.epoch) == exec.ReplicaId && op.pbft.activeView) {
		logger.Debug("Invalid execute from %d", exec.ReplicaId)
		return
	}

	if exec.BlockNumber != op.blockNumber+1 {
		logger.Debug("Invalid block number in execute: expected %d, got %d",
			op.blockNumber+1, exec.BlockNumber)
		return
	}

	logger.Debug("Sieve replica %d received exec from %d, epoch=%d, blockNo=%d",
		op.id, exec.ReplicaId, exec.View, exec.BlockNumber)

	blockchainSize, _ := op.stack.GetBlockchainSize()
	blockchainSize--
	if op.blockNumber != blockchainSize {
		logger.Critical("Sieve replica %d block number and ledger blockchain size diverged: blockNo=%d, blockchainSize=%d", op.id, op.blockNumber, blockchainSize)
		return
	}

	op.currentReq = base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(exec.Request))
	op.blockNumber++

	op.begin()
	tx := &pb.Transaction{}
	proto.Unmarshal(exec.Request, tx)
	op.currentTx = []*pb.Transaction{tx}
	op.stack.ExecTxs(op.currentReq, op.currentTx)
	hash, err := op.previewCommit(op.blockNumber)
	if err != nil {
		err = fmt.Errorf("Sieve replica %d ignoring execute: %s", op.id, err)
		logger.Error(err.Error())
		op.blockNumber--
		op.currentReq = ""
		return
	}

	op.currentResult = hash

	logger.Debug("Sieve replica %d executed blockNo=%d, request=%s, result=%s", op.id, op.blockNumber, op.currentReq, op.currentResult)

	// for simplicity's sake, we use the pbft timer
	op.pbft.startTimer(op.pbft.requestTimeout)

	verify := &Verify{
		View:          exec.View,
		BlockNumber:   exec.BlockNumber,
		RequestDigest: op.currentReq,
		ResultDigest:  op.currentResult,
		ReplicaId:     op.id,
	}
	op.pbft.sign(verify)

	logger.Debug("Sieve replica %d sending verify blockNo=%d",
		op.id, verify.BlockNumber)
	op.broadcastMsg(&SieveMessage{&SieveMessage_Verify{verify}})
	op.recvVerify(verify)
}