Esempio n. 1
0
// Serialize converts this Scan into a serialized protobuf message ready
// to be sent to an HBase node.
func (s *Scan) Serialize() ([]byte, error) {
	scan := &pb.ScanRequest{
		Region:       s.regionSpecifier(),
		CloseScanner: &s.closeScanner,
		NumberOfRows: &s.numberOfRows,
	}
	if s.scannerID != math.MaxUint64 {
		scan.ScannerId = &s.scannerID
		return proto.Marshal(scan)
	}
	scan.Scan = &pb.Scan{
		Column:    familiesToColumn(s.families),
		StartRow:  s.startRow,
		StopRow:   s.stopRow,
		TimeRange: &pb.TimeRange{},
	}
	if s.maxVersions != DefaultMaxVersions {
		scan.Scan.MaxVersions = &s.maxVersions
	}
	if s.fromTimestamp != MinTimestamp {
		scan.Scan.TimeRange.From = &s.fromTimestamp
	}
	if s.toTimestamp != MaxTimestamp {
		scan.Scan.TimeRange.To = &s.toTimestamp
	}

	if s.filters != nil {
		pbFilter, err := s.filters.ConstructPBFilter()
		if err != nil {
			return nil, err
		}
		scan.Scan.Filter = pbFilter
	}
	return proto.Marshal(scan)
}
Esempio n. 2
0
//挑战其他玩家
func (this *Player) ChallengePlayer(type_ int32, other_role_id int64) {
	result4C := new(protocol.StageBase_ChallengePlayerResult)
	if type_ == 1 { //挂机挑战其他玩家
		result := this.Guaji_Stage.IsCanPk(this.PlayerId, other_role_id)
		result4C.IsCanChange = &result

		if !result { //不能挑战直接返回
			encObj, _ := proto.Marshal(result4C)
			SendPackage(*this.conn, 1111, encObj)
		}

		Heros := make(map[int32]*HeroStruct)
		if value, ok := word.players[other_role_id]; ok {
			for k, v := range value.Heros { //遍历对应玩家的所有英雄列表
				if v.Hero_Info.Pos_stage > 0 { //关卡上阵英雄
					Heros[k] = v
				}
			}
			Game_HeroStruct := this.GetHeroStruct(Heros)
			result4C.Team_2 = Game_HeroStruct
		}

		encObj, _ := proto.Marshal(result4C)
		SendPackage(*this.conn, 1111, encObj)
	}
}
Esempio n. 3
0
func (this *clientCodec) WriteRequest(rpcreq *rpc.Request, param interface{}) error {
	rr := *rpcreq
	req := &Request{}

	this.mutex.Lock()
	req.Id = proto.Uint64(this.next)
	this.next++
	this.pending[*req.Id] = &rr
	this.mutex.Unlock()

	req.Method = proto.String(rpcreq.ServiceMethod)
	if msg, ok := param.(proto.Message); ok {
		body, err := proto.Marshal(msg)
		if err != nil {
			return err
		}
		req.Body = body
	} else {
		return fmt.Errorf("marshal request param error: %s", param)
	}

	f, err := proto.Marshal(req)
	if err != nil {
		return err
	}

	if err := write(this.w, f); err != nil {
		return err
	}

	return nil
}
Esempio n. 4
0
// WriteResponse writes a response on the codec.
func (c *pbServerCodec) WriteResponse(r *rpc.Response, body interface{}, last bool) (err error) {
	// Use a mutex to guarantee the header/body are written in the correct order.
	c.mu.Lock()
	defer c.mu.Unlock()
	rtmp := &Response{ServiceMethod: &r.ServiceMethod, Seq: &r.Seq, Error: &r.Error}
	data, err := proto.Marshal(rtmp)
	if err != nil {
		return
	}
	_, err = WriteNetString(c.rwc, data)
	if err != nil {
		return
	}

	if pb, ok := body.(proto.Message); ok {
		data, err = proto.Marshal(pb)
		if err != nil {
			return
		}
	} else {
		data = nil
	}
	_, err = WriteNetString(c.rwc, data)
	if err != nil {
		return
	}

	if flusher, ok := c.rwc.(flusher); ok {
		err = flusher.Flush()
	}
	return
}
Esempio n. 5
0
//TestUpgradeNonExistChaincode tests upgrade non exist chaincode
func TestUpgradeNonExistChaincode(t *testing.T) {
	initialize()

	scc := new(LifeCycleSysCC)
	stub := shim.NewMockStub("lccc", scc)

	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")})
	var b []byte
	if b, err = proto.Marshal(cds); err != nil || b == nil {
		t.Fatalf("Marshal DeploymentSpec failed")
	}

	args := [][]byte{[]byte(DEPLOY), []byte("test"), b}
	if _, err := stub.MockInvoke("1", args); err != nil {
		t.Fatalf("Deploy chaincode error: %v", err)
	}

	newCds, err := constructDeploymentSpec("example03", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")})
	var newb []byte
	if newb, err = proto.Marshal(newCds); err != nil || newb == nil {
		t.Fatalf("Marshal DeploymentSpec failed")
	}

	args = [][]byte{[]byte(UPGRADE), []byte("test"), newb}
	_, err = stub.MockInvoke("1", args)
	if _, ok := err.(NotFoundErr); !ok {
		t.FailNow()
	}
}
Esempio n. 6
0
func (c *serverCodec) WriteResponse(r *rpc.Response, result interface{}) error {
	rsp := &PbRpcResponse{Id: &r.Seq}

	if r.Error != "" {
		rsp.Error = &r.Error
	} else {
		protoResult, ok := result.(proto.Message)
		if !ok {
			return errors.New("Invalid type given")
		}
		data, err := proto.Marshal(protoResult)
		if err != nil {
			return err
		}
		rsp.Result = data
	}

	data, err := proto.Marshal(rsp)
	if err != nil {
		return err
	}
	_, err = WriteRpc(c.rwc, data)

	return err
}
Esempio n. 7
0
func TestLedgerReadWrite(t *testing.T) {
	localConf := localconfig.Load()
	localConf.General.OrdererType = provisional.ConsensusTypeSbft
	genesis := provisional.New(localConf).GenesisBlock()
	_, rl := ramledger.New(10, genesis)
	b := Backend{ledger: rl}

	header := []byte("header")
	e1 := &cb.Envelope{Payload: []byte("data1")}
	e2 := &cb.Envelope{Payload: []byte("data2")}
	ebytes1, _ := proto.Marshal(e1)
	ebytes2, _ := proto.Marshal(e2)
	data := [][]byte{ebytes1, ebytes2}
	sgns := make(map[uint64][]byte)
	sgns[uint64(1)] = []byte("sgn1")
	sgns[uint64(22)] = []byte("sgn22")
	batch := simplebft.Batch{Header: header, Payloads: data, Signatures: sgns}

	b.Deliver(&batch)
	batch2 := b.LastBatch()

	if !reflect.DeepEqual(batch, *batch2) {
		t.Errorf("The wrong batch was returned by LastBatch after Deliver: %v (original was: %v)", batch2, &batch)
	}
}
Esempio n. 8
0
// Returns a valid protobuf collection in bytes and the related jobs
func GetTestProtobufCollectionBody(userId uint32, numberOfPayloads int) (*TrackBodyCollection, []*EventAction) {
	collection, wrongCollection, incompleteCollection := GetTestCollectionPairs(userId, numberOfPayloads)
	collectionBytestream, _ := proto.Marshal(collection)
	disturbedCollectionBytestream, _ := proto.Marshal(wrongCollection)
	incompleteCollectionByteStream, _ := proto.Marshal(incompleteCollection)
	return &TrackBodyCollection{collectionBytestream, disturbedCollectionBytestream, incompleteCollectionByteStream}, GetJobsFromCollection(collection)
}
Esempio n. 9
0
// WriteRequest - implement rpc.ClientCodec interface.
func (c *pbClientCodec) WriteRequest(r *rpc.Request, body interface{}) (err error) {
	// Use a mutex to guarantee the header/body are written in the correct order.
	c.mu.Lock()
	defer c.mu.Unlock()

	// This is protobuf, of course we copy it.
	pbr := &Request{ServiceMethod: &r.ServiceMethod, Seq: &r.Seq}
	data, err := proto.Marshal(pbr)
	if err != nil {
		return
	}
	_, err = WriteNetString(c.rwc, data)
	if err != nil {
		return
	}

	// Of course this is a protobuf! Trust me or detonate the program.
	data, err = proto.Marshal(body.(proto.Message))
	if err != nil {
		return
	}
	_, err = WriteNetString(c.rwc, data)
	if err != nil {
		return
	}

	if flusher, ok := c.rwc.(flusher); ok {
		err = flusher.Flush()
	}
	return
}
Esempio n. 10
0
// Insert can insert record into a btree
func (t *Btree) insert(record TreeLog) error {
	tnode, err := t.getTreeNode(t.GetRoot())
	if err != nil {
		if err.Error() != "no data" {
			return err
		}
		nnode := t.newTreeNode()
		nnode.NodeType = proto.Int32(isLeaf)
		_, err = nnode.insertRecord(record, t)
		if err == nil {
			t.Nodes[nnode.GetId()], err = proto.Marshal(nnode)
		}
		t.Root = proto.Int64(nnode.GetId())
		return err
	}
	clonednode, err := tnode.insertRecord(record, t)
	if err == nil && len(clonednode.GetKeys()) > int(t.GetNodeMax()) {
		nnode := t.newTreeNode()
		nnode.NodeType = proto.Int32(isNode)
		key, left, right := clonednode.split(t)
		nnode.insertOnce(key, left, right, t)
		t.Nodes[nnode.GetId()], err = proto.Marshal(nnode)
		t.Root = proto.Int64(nnode.GetId())
	} else {
		t.Root = proto.Int64(clonednode.GetId())
	}
	return err
}
Esempio n. 11
0
func TestVerifyHostAttestation_rootHost(t *testing.T) {
	domain := generateDomain(t)
	policyKey, policyCert := domain.Keys, domain.Keys.Cert
	hostKey, hostAtt := generateAttestation(t, policyKey, hostName)
	programKey, programAtt := generateAttestation(t, hostKey, programName)
	rawEnd, err := proto.Marshal(hostAtt)
	if err != nil {
		t.Fatal("Error serializing attestation.")
	}
	programAtt.SerializedEndorsements = [][]byte{rawEnd}
	rawAtt, err := proto.Marshal(programAtt)
	if err != nil {
		t.Fatal("Error serializing attestation.")
	}
	certPool := x509.NewCertPool()
	certPool.AddCert(policyCert)
	speaker, key, prog, err := VerifyHostAttestation(rawAtt, domain, certPool)
	if err != nil {
		t.Fatal("Test attesation failed verification checks.", err)
	}
	if !programName.Identical(prog) {
		t.Fatal("Attestation program name not identical to expected program name.")
	}
	if !programKey.SigningKey.ToPrincipal().Identical(key) {
		t.Fatal("Attestation program key not identical to expected program key.")
	}
	if !hostKey.SigningKey.ToPrincipal().Identical(speaker) {
		t.Fatal("Attestation host key not identical to expected host key.")
	}
}
Esempio n. 12
0
func Action1Handler(user *User, data []byte) {

	// request body unmarshaling
	req := new(gs_protocol.ReqAction1)
	err := proto.Unmarshal(data, req)
	gs.CheckError(err)

	// TODO create business logic for Action1 Type
	if DEBUG {
		gs.Log("Action1 userID : ", gs.Itoa64(req.GetUserID()))
	}

	// broadcast message
	notifyMsg := new(gs_protocol.NotifyAction1Msg)
	notifyMsg.UserID = proto.Int64(user.userID)
	msg, err := proto.Marshal(notifyMsg)
	gs.CheckError(err)

	user.SendToAll(NewMessage(user.userID, gs_protocol.Type_NotifyAction1, msg))

	// response body marshaling
	res := new(gs_protocol.ResAction1)
	res.UserID = proto.Int64(user.userID)
	res.Result = proto.Int32(1) // is success?
	msg, err = proto.Marshal(res)
	gs.CheckError(err)
	user.Push(NewMessage(user.userID, gs_protocol.Type_DefinedAction1, msg))
}
Esempio n. 13
0
func writeEvent(ev *Event, writer io.Writer) error {
	if len(ev.raw) > 0 {
		_, err := writer.Write(ev.raw)
		return err
	}
	var buf bytes.Buffer
	dataBuf, err := proto.Marshal(ev.Msg)
	if nil != err {
		return err
	}
	msgtype := proto.MessageName(ev.Msg)
	ev.MsgType = &msgtype
	headbuf, _ := proto.Marshal(ev)
	headerLen := uint32(len(headbuf))

	// length = msglength(3byte) + headerlen(1byte)
	length := uint32(len(dataBuf))
	length = (length << 8) + headerLen
	buf.Write(MAGIC_EVENT_HEADER)
	binary.Write(&buf, binary.LittleEndian, length)

	buf.Write(headbuf)
	buf.Write(dataBuf)
	_, err = buf.WriteTo(writer)

	return err
}
Esempio n. 14
0
func (op *obcBatch) sendBatch() error {
	op.stopBatchTimer()
	// assemble new Request message
	txs := make([]*pb.Transaction, len(op.batchStore))
	var i int
	for d, req := range op.batchStore {
		txs[i] = &pb.Transaction{}
		err := proto.Unmarshal(req.Payload, txs[i])
		if err != nil {
			err = fmt.Errorf("Unable to unpack payload of request %d", i)
			logger.Error("%s", err)
			return err
		}
		i++
		delete(op.batchStore, d) // clean up
	}
	tb := &pb.TransactionBlock{Transactions: txs}
	tbPacked, err := proto.Marshal(tb)
	if err != nil {
		err = fmt.Errorf("Unable to pack transaction block for new batch request")
		logger.Error("%s", err)
		return err
	}
	// process internally
	op.pbft.request(tbPacked)
	// broadcast
	batchReq := &Request{Payload: tbPacked}
	msg := &Message{&Message_Request{batchReq}}
	msgRaw, _ := proto.Marshal(msg)
	op.broadcast(msgRaw)

	return nil
}
Esempio n. 15
0
// NewChaincodeDeployTransaction is used to deploy chaincode.
func NewChaincodeDeployTransaction(chaincodeDeploymentSpec *ChaincodeDeploymentSpec, uuid string) (*Transaction, error) {
	transaction := new(Transaction)
	transaction.Type = Transaction_CHAINCODE_DEPLOY
	transaction.Uuid = uuid
	transaction.Timestamp = util.CreateUtcTimestamp()
	cID := chaincodeDeploymentSpec.ChaincodeSpec.GetChaincodeID()
	if cID != nil {
		data, err := proto.Marshal(cID)
		if err != nil {
			return nil, fmt.Errorf("Could not marshal chaincode : %s", err)
		}
		transaction.ChaincodeID = data
	}
	//if chaincodeDeploymentSpec.ChaincodeSpec.GetCtorMsg() != nil {
	//	transaction.Function = chaincodeDeploymentSpec.ChaincodeSpec.GetCtorMsg().Function
	//	transaction.Args = chaincodeDeploymentSpec.ChaincodeSpec.GetCtorMsg().Args
	//}
	data, err := proto.Marshal(chaincodeDeploymentSpec)
	if err != nil {
		logger.Errorf("Error mashalling payload for chaincode deployment: %s", err)
		return nil, fmt.Errorf("Could not marshal payload for chaincode deployment: %s", err)
	}
	transaction.Payload = data
	return transaction, nil
}
Esempio n. 16
0
func TestMultiPart(t *testing.T) {
	stream := &fakeStream{
		recvPackets: make(chan shanPacket, 5),
		sendPackets: make(chan shanPacket, 5),
	}

	controller := setupTestController(stream)

	subHeader := &Spotify.Header{
		Uri: proto.String("hm://searchview/km/v2/search/Future"),
	}
	subHeaderData, _ := proto.Marshal(subHeader)

	header := &Spotify.Header{
		Uri:         proto.String("hm://searchview/km/v2/search/Future"),
		ContentType: proto.String("application/json; charset=UTF-8"),
		StatusCode:  proto.Int32(200),
	}
	body := []byte("{searchResults: {tracks: [], albums: [], tracks: []}}")

	headerData, _ := proto.Marshal(header)
	seq := []byte{0, 0, 0, 1}

	p0, _ := encodeMercuryHead([]byte{0, 0, 0, 0}, 1, 1)
	binary.Write(p0, binary.BigEndian, uint16(len(subHeaderData)))
	p0.Write(subHeaderData)

	p1, _ := encodeMercuryHead(seq, 1, 0)
	binary.Write(p1, binary.BigEndian, uint16(len(headerData)))
	p1.Write(headerData)

	p2, _ := encodeMercuryHead(seq, 1, 1)
	binary.Write(p2, binary.BigEndian, uint16(len(body)))
	p2.Write(body)

	didRecieveCallback := false
	controller.session.mercurySendRequest(mercuryRequest{
		method:  "SEND",
		uri:     "hm://searchview/km/v2/search/Future",
		payload: [][]byte{},
	}, func(res mercuryResponse) {
		didRecieveCallback = true
		if string(res.payload[0]) != string(body) {
			t.Errorf("bad body received")
		}
	})

	stream.recvPackets <- shanPacket{cmd: 0xb2, buf: p0.Bytes()}
	stream.recvPackets <- shanPacket{cmd: 0xb2, buf: p1.Bytes()}
	stream.recvPackets <- shanPacket{cmd: 0xb2, buf: p2.Bytes()}

	controller.session.poll()
	controller.session.poll()
	controller.session.poll()

	if !didRecieveCallback {
		t.Errorf("never received callback")
	}

}
Esempio n. 17
0
func getfetchMsg(key [sha256.Size]byte) []byte {

	msg := new(fsMsgs.NetworkMessage)
	msg.Proto = proto.Uint32(2)
	appMsg := new(fsMsgs.AppMessage)
	fsMsg := new(fsMsgs.AppMessage_FileSystemMessage)
	command := fsMsgs.AppMessage_Command(fsMsgs.AppMessage_Command_value["FETCH"])
	fsMsg.Cmd = &command
	fetchMsg := new(fsMsgs.FetchMessage)
	fetchMsg.Key = proto.String(string(key[:sha256.Size]))
	fsMsg.Fmsg = fetchMsg
	appMsg.Msg = fsMsg

	appdata, err := proto.Marshal(appMsg)
	if err != nil {
		log.Fatal("marshaling error: ", err)
	}
	msg.Msg = proto.String(string(appdata))

	data, err := proto.Marshal(msg)
	if err != nil {
		log.Fatal("marshaling error: ", err)
	}

	return data
}
Esempio n. 18
0
func (c *mercuryCodec) Write(m *codec.Message, b interface{}) error {
	switch m.Type {
	case codec.Request:
		data, err := proto.Marshal(b.(proto.Message))
		if err != nil {
			return err
		}
		c.rwc.Write(data)
		m.Header["Content-Encoding"] = "request"
		m.Header["Service"] = m.Target
		m.Header["Endpoint"] = m.Method
	case codec.Response:
		m.Header["Content-Encoding"] = "response"
		data, err := proto.Marshal(b.(proto.Message))
		if err != nil {
			return err
		}
		c.rwc.Write(data)
	case codec.Publication:
		data, err := proto.Marshal(b.(proto.Message))
		if err != nil {
			return err
		}
		c.rwc.Write(data)
	default:
		return fmt.Errorf("Unrecognised message type: %v", m.Type)
	}
	return nil
}
Esempio n. 19
0
func getstoreMsg(key [sha256.Size]byte, document []byte) []byte {

	msg := new(fsMsgs.NetworkMessage)
	msg.Proto = proto.Uint32(2)
	appMsg := new(fsMsgs.AppMessage)
	fsMsg := new(fsMsgs.AppMessage_FileSystemMessage)
	command := fsMsgs.AppMessage_Command(fsMsgs.AppMessage_Command_value["STORE"])
	fsMsg.Cmd = &command
	storeMsg := new(fsMsgs.StoreMessage)
	storeMsg.Key = proto.String(string(key[:sha256.Size]))
	storeMsg.Document = proto.String(string(document))
	fsMsg.Smsg = storeMsg
	appMsg.Msg = fsMsg

	appdata, err := proto.Marshal(appMsg)
	if err != nil {
		log.Fatal("marshaling error: ", err)
	}
	msg.Msg = proto.String(string(appdata))

	data, err := proto.Marshal(msg)
	if err != nil {
		log.Fatal("marshaling error: ", err)
	}

	return data
}
Esempio n. 20
0
//TestUpgrade tests the upgrade function
func TestUpgrade(t *testing.T) {
	initialize()

	scc := new(LifeCycleSysCC)
	stub := shim.NewMockStub("lccc", scc)

	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")})
	var b []byte
	if b, err = proto.Marshal(cds); err != nil || b == nil {
		t.Fatalf("Marshal DeploymentSpec failed")
	}

	args := [][]byte{[]byte(DEPLOY), []byte("test"), b}
	if _, err := stub.MockInvoke("1", args); err != nil {
		t.Fatalf("Deploy chaincode error: %v", err)
	}

	newCds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")})
	var newb []byte
	if newb, err = proto.Marshal(newCds); err != nil || newb == nil {
		t.Fatalf("Marshal DeploymentSpec failed")
	}

	args = [][]byte{[]byte(UPGRADE), []byte("test"), newb}
	version, err := stub.MockInvoke("1", args)
	if err != nil {
		t.Fatalf("Upgrade chaincode error: %v", err)
	}

	expectVer := "1"
	newVer := string(version)
	if newVer != expectVer {
		t.Fatalf("Upgrade chaincode version error, expected %s, got %s", expectVer, newVer)
	}
}
Esempio n. 21
0
func (c *clientCodec) WriteRequest(r *rpc.Request, params interface{}) error {
	c.m.Lock()
	defer c.m.Unlock()

	req := &PbRpcRequest{Id: &r.Seq, Method: &r.ServiceMethod}

	protoParams, ok := params.(proto.Message)
	if !ok {
		e := errors.New("Invalid type given")
		log.Print(e)
		return e
	}

	data, err := proto.Marshal(protoParams)
	if err != nil {
		return err
	}
	req.Params = data

	data, err = proto.Marshal(req)
	if err != nil {
		return err
	}

	_, err = WriteRpc(c.rwc, data)

	return err
}
Esempio n. 22
0
// Seal encrypts data so only certain hosted programs can unseal it. Note that
// at least some TPMs can only seal up to 149 bytes of data. So, we employ a
// hybrid encryption scheme that seals a key and uses the key to encrypt the
// data separately. We use the keys infrastructure to perform secure and
// flexible encryption.
func (tt *TPM2Tao) Seal(data []byte, policy string) ([]byte, error) {
	rh, err := tt.loadRoot()
	if err != nil {
		return nil, err
	}
	defer tpm2.FlushContext(tt.rw, rh)

	sk, policy_digest, err := tt.loadSession()
	if err != nil {
		return nil, errors.New("Can't load root key")
	}
	defer tpm2.FlushContext(tt.rw, sk)

	if policy != SealPolicyDefault {
		return nil, errors.New("tpm-specific policies are not yet implemented")
	}

	crypter, err := GenerateCrypter()
	if err != nil {
		return nil, err
	}
	defer ZeroBytes(crypter.aesKey)
	defer ZeroBytes(crypter.hmacKey)

	c, err := crypter.Encrypt(data)
	if err != nil {
		return nil, err
	}

	ck, err := MarshalCrypterProto(crypter)
	if err != nil {
		return nil, err
	}
	defer ZeroBytes(ck.Key)

	ckb, err := proto.Marshal(ck)
	if err != nil {
		return nil, err
	}
	defer ZeroBytes(ckb)

	priv, pub, err := tpm2.AssistSeal(tt.rw, rh, ckb,
		"", tt.password, tt.pcrs, policy_digest)
	if err != nil {
		return nil, err
	}

	// encode pub and priv
	s := EncodeTwoBytes(pub, priv)

	h := &HybridSealedData{
		SealedKey:     s,
		EncryptedData: c,
	}

	return proto.Marshal(h)
}
Esempio n. 23
0
func TestRejectBadConfig(t *testing.T) {
	cf := NewFilter(&mockConfigManager{err: fmt.Errorf("Error")})
	config, _ := proto.Marshal(&cb.ConfigurationEnvelope{})
	configBytes, _ := proto.Marshal(&cb.Payload{Header: &cb.Header{ChainHeader: &cb.ChainHeader{Type: int32(cb.HeaderType_CONFIGURATION_TRANSACTION)}}, Data: config})
	result, _ := cf.Apply(&cb.Envelope{
		Payload: configBytes,
	})
	if result != filter.Reject {
		t.Fatalf("Should have rejected bad config message")
	}
}
Esempio n. 24
0
func main() {
	// Configure logging.
	log.SetFlags(0)
	log.SetPrefix("protoc-gen-proto: ")

	// Read input from the protoc compiler.
	data, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		log.Fatal(err, ": failed to read input")
	}

	// Unmarshal the protoc generation request.
	request := &plugin.CodeGeneratorRequest{}
	if err := proto.Unmarshal(data, request); err != nil {
		log.Fatal(err, ": failed to parse input proto")
	}
	if len(request.FileToGenerate) == 0 {
		log.Fatal(err, ": no input files")
	}

	// Parse the command-line parameters.
	params := util.ParseParams(request)

	// Determine the correct output file name.
	name := "out.gob"
	if v, ok := params["out"]; ok {
		name = v
	}

	// Perform generation.
	response := &plugin.CodeGeneratorResponse{}
	data, err = proto.Marshal(request)
	if err != nil {
		response.Error = proto.String(err.Error())
	} else {
		response.File = []*plugin.CodeGeneratorResponse_File{
			&plugin.CodeGeneratorResponse_File{
				Name:    proto.String(name),
				Content: proto.String(string(data)),
			},
		}
	}

	// Marshal the results and write back to the protoc compiler.
	data, err = proto.Marshal(response)
	if err != nil {
		log.Fatal(err, ": failed to marshal output proto")
	}
	_, err = io.Copy(os.Stdout, bytes.NewReader(data))
	if err != nil {
		log.Fatal(err, ": failed to write output proto")
	}
}
Esempio n. 25
0
func TestCorruptedCiphertext(t *testing.T) {
	c, err := GenerateCrypter()
	if err != nil {
		t.Fatal(err.Error())
	}

	data := []byte("Test data to encrypt")
	crypted, err := c.Encrypt(data)
	if err != nil {
		t.Fatal(err.Error())
	}

	var ed EncryptedData
	if err := proto.Unmarshal(crypted, &ed); err != nil {
		t.Fatal("Could not unmarshal the encrypted data")
	}

	// Read random data for the ciphertext.
	if _, err := rand.Read(ed.Ciphertext); err != nil {
		t.Fatal("Could not read random data into the ciphertext")
	}

	crypted2, err := proto.Marshal(&ed)
	if err != nil {
		t.Fatal("Could not marshal the corrupted ciphertext")
	}

	if _, err := c.Decrypt(crypted2); err == nil {
		t.Fatal("Incorrectly succeeded at decrypting corrupted ciphertext")
	}

	// Corrupt each bit individually and make sure the test fails for any
	// single bit flip. The range is over the first ciphertext, but this is
	// identical to the range of the unmarshalled ciphertext in this loop.
	for i := range ed.Ciphertext {
		var ed2 EncryptedData
		if err := proto.Unmarshal(crypted, &ed2); err != nil {
			t.Fatal("Could not unmarshal the encrypted data a second time")
		}

		// Corrupt a single bit in the ciphertext.
		ed2.Ciphertext[i] ^= ed2.Ciphertext[i]

		crypted3, err := proto.Marshal(&ed2)
		if err != nil {
			t.Fatal("Could not marshal a second corrupted ciphertext")
		}

		if _, err := c.Decrypt(crypted3); err == nil {
			t.Fatal("Incorrectly succeeded at decrypting a second corrupted ciphertext")
		}
	}
}
Esempio n. 26
0
func TestNewViewTimeout(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping timeout test")
	}

	net := makeTestnet(1, func(inst *instance) {
		makeTestnetPbftCore(inst)
		inst.pbft.newViewTimeout = 100 * time.Millisecond
		inst.pbft.requestTimeout = inst.pbft.newViewTimeout
		inst.pbft.lastNewViewTimeout = inst.pbft.newViewTimeout
	})
	defer net.close()

	replica1Disabled := false
	net.filterFn = func(src int, dst int, msg []byte) []byte {
		if dst == -1 && src == 1 && replica1Disabled {
			return nil
		}
		return msg
	}

	txTime := &gp.Timestamp{Seconds: 1, Nanos: 0}
	tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_NEW, Timestamp: txTime}
	txPacked, _ := proto.Marshal(tx)
	msg := &Message{&Message_Request{&Request{Payload: txPacked}}}
	msgPacked, _ := proto.Marshal(msg)

	go net.processContinually()

	// This will eventually trigger 1's request timeout
	// We check that one single timed out replica will not keep trying to change views by itself
	net.replicas[1].pbft.receive(msgPacked)
	time.Sleep(1 * time.Second)

	// This will eventually trigger 3's request timeout, which will lead to a view change to 1.
	// However, we disable 1, which will disable the new-view going through.
	// This checks that replicas will automatically move to view 2 when the view change times out.
	// However, 2 does not know about the missing request, and therefore the request will not be
	// pre-prepared and finally executed.  This will lead to another view-change timeout, even on
	// the replicas that never saw the request (e.g. 0)
	// Finally, 3 will be new primary and pre-prepare the missing request.
	replica1Disabled = true
	net.replicas[3].pbft.receive(msgPacked)
	time.Sleep(1 * time.Second)

	net.close()
	for i, inst := range net.replicas {
		if inst.pbft.view != 3 {
			t.Fatalf("Should have reached view 3, got %d instead for replica %d", inst.pbft.view, i)
		}
	}
}
Esempio n. 27
0
func (c *context) Call(service, method string, in, out appengine_internal.ProtoMessage, opts *appengine_internal.CallOptions) error {
	req, err := proto.Marshal(in)
	if err != nil {
		return fmt.Errorf("error marshalling request: %v", err)
	}

	remReq := &pb.Request{
		ServiceName: proto.String(service),
		Method:      proto.String(method),
		Request:     req,
		// NOTE: RequestId is unused in the server.
	}

	req, err = proto.Marshal(remReq)
	if err != nil {
		return fmt.Errorf("proto.Marshal: %v", err)
	}

	// TODO: Respect opts.Timeout?
	resp, err := c.client.Post(c.url, "application/octet-stream", bytes.NewReader(req))
	if err != nil {
		return fmt.Errorf("error sending request: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("bad response %d; body: %q", resp.StatusCode, body)
	}
	if err != nil {
		return fmt.Errorf("failed reading response: %v", err)
	}
	remResp := &pb.Response{}
	if err := proto.Unmarshal(body, remResp); err != nil {
		return fmt.Errorf("error unmarshalling response: %v", err)
	}

	if ae := remResp.GetApplicationError(); ae != nil {
		return &appengine_internal.APIError{
			Code:    ae.GetCode(),
			Detail:  ae.GetDetail(),
			Service: service,
		}
	}

	if remResp.Response == nil {
		return fmt.Errorf("unexpected response: %s", proto.MarshalTextString(remResp))
	}

	return proto.Unmarshal(remResp.Response, out)
}
Esempio n. 28
0
func TestVerifyHostAttestation_stackedHost(t *testing.T) {
	aikblob, err := ioutil.ReadFile("./aikblob")
	if err != nil {
		t.Skip("Skipping tests, since there's no ./aikblob file")
	}
	tpmtao, err := tao.NewTPMTao("/dev/tpm0", aikblob, []int{17, 18})
	if err != nil {
		t.Skip("Couldn't create a new TPM Tao:", err)
	}
	tt, ok := tpmtao.(*tao.TPMTao)
	if !ok {
		t.Fatal("Failed to create the right kind of Tao object from NewTPMTao")
	}
	defer tao.CleanUpTPMTao(tt)
	hwPublicKey, err := tpm.UnmarshalRSAPublicKey(aikblob)
	if err != nil {
		t.Fatal(err)
	}

	domain := generateDomain(t)
	policyKey, policyCert := domain.Keys, domain.Keys.Cert
	hwCert := generateEndorsementCertficate(t, policyKey, hwPublicKey, policyCert)
	hostKey, hostAtt := generateTpmAttestation(t, tt, hostName)
	programKey, programAtt := generateAttestation(t, hostKey, programName)
	rawEnd1, err := proto.Marshal(hostAtt)
	if err != nil {
		t.Fatal("Error serializing attestation.")
	}
	rawEnd2 := hwCert.Raw
	programAtt.SerializedEndorsements = [][]byte{rawEnd1, rawEnd2}
	rawAtt, err := proto.Marshal(programAtt)
	if err != nil {
		t.Fatal("Error serializing attestation.")
	}
	certPool := x509.NewCertPool()
	certPool.AddCert(policyCert)
	speaker, key, prog, err := VerifyHostAttestation(rawAtt, domain, certPool)
	if err != nil {
		t.Fatal("Test attesation failed verification checks.", err)
	}
	if !programName.Identical(prog) {
		t.Fatal("Attestation program name not identical to expected program name.")
	}
	if !programKey.SigningKey.ToPrincipal().Identical(key) {
		t.Fatal("Attestation program key not identical to expected program key.")
	}
	if !hostKey.SigningKey.ToPrincipal().Identical(speaker) {
		t.Fatal("Attestation host key not identical to expected host key.")
	}
}
Esempio n. 29
0
func writeResponse(w io.Writer, id uint64, serr string, response proto.Message) (err error) {
	// clean response if error
	if serr != "" {
		response = nil
	}

	// marshal response
	pbResponse := []byte{}
	if response != nil {
		pbResponse, err = proto.Marshal(response)
		if err != nil {
			return err
		}
	}

	// compress serialized proto data
	compressedPbResponse := snappy.Encode(nil, pbResponse)

	// generate header
	header := &wire.ResponseHeader{
		Id:                          proto.Uint64(id),
		Error:                       proto.String(serr),
		RawResponseLen:              proto.Uint32(uint32(len(pbResponse))),
		SnappyCompressedResponseLen: proto.Uint32(uint32(len(compressedPbResponse))),
		Checksum:                    proto.Uint32(crc32.ChecksumIEEE(compressedPbResponse)),
	}

	// check header size
	pbHeader, err := proto.Marshal(header)
	if err != err {
		return
	}
	if uint32(len(pbHeader)) > wire.Default_Const_MaxHeaderLen {
		return fmt.Errorf("protorpc.writeResponse: header larger than max_header_len: %d.",
			len(pbHeader),
		)
	}

	// send header (more)
	if err = sendFrame(w, pbHeader); err != nil {
		return
	}

	// send body (end)
	if err = sendFrame(w, compressedPbResponse); err != nil {
		return
	}

	return nil
}
Esempio n. 30
0
func (transport *ZMQTransport) zmq_find_successors_handler(request *ChordMsg, w chan *ChordMsg) {
	pbMsg := request.TransportMsg.(PBProtoFindSuccessors)
	key := pbMsg.GetKey()
	dest := VnodeFromProtobuf(pbMsg.GetDest())

	// make sure destination vnode exists locally
	local_vn, err := transport.getVnodeHandler(dest)
	if err != nil {
		errorMsg := transport.newErrorMsg("ZMQ::FindSuccessorsHandler - " + err.Error())
		w <- errorMsg
		return
	}
	succs, forward_vn, err := local_vn.FindSuccessors(key, int(pbMsg.GetLimit()))
	if err != nil {
		errorMsg := transport.newErrorMsg("ZMQ::FindSuccessorsHandler - " + err.Error())
		w <- errorMsg
		return
	}

	// if forward_vn is not set, return the list
	if forward_vn == nil {
		pblist := new(PBProtoListVnodesResp)
		for _, s := range succs {
			pblist.Vnodes = append(pblist.Vnodes, s.ToProtobuf())
		}
		pbdata, err := proto.Marshal(pblist)
		if err != nil {
			errorMsg := transport.newErrorMsg("ZMQ::FindSuccessorsHandler - failed to marshal response - " + err.Error())
			w <- errorMsg
			return
		}
		w <- &ChordMsg{
			Type: PbListVnodesResp,
			Data: pbdata,
		}
		return
	}
	// send forward response
	pbfwd := &PBProtoForward{Vnode: forward_vn.ToProtobuf()}
	pbdata, err := proto.Marshal(pbfwd)
	if err != nil {
		errorMsg := transport.newErrorMsg("ZMQ::FindSuccessorsHandler - failed to marshal forward response - " + err.Error())
		w <- errorMsg
		return
	}
	w <- &ChordMsg{
		Type: PbForward,
		Data: pbdata,
	}
}