本文整理汇总了Golang中github.com/golang/protobuf/proto.Unmarshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Unmarshal函数的具体用法?Golang Unmarshal怎么用?Golang Unmarshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Unmarshal函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: LoadACLGuard
// LoadACLGuard restores a set of rules saved with Save. It replaces any rules
// in the ACLGuard with the rules it loaded. In the process, it also checks the
// signature created during the Save process.
func LoadACLGuard(key *Verifier, config ACLGuardDetails) (Guard, error) {
b, err := ioutil.ReadFile(config.GetSignedAclsPath())
if err != nil {
return nil, err
}
var sigACL SignedACLSet
if err := proto.Unmarshal(b, &sigACL); err != nil {
return nil, err
}
ok, err := key.Verify(sigACL.SerializedAclset, ACLGuardSigningContext, sigACL.Signature)
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("the signature on the file didn't pass verification")
}
var acls ACLSet
if err := proto.Unmarshal(sigACL.SerializedAclset, &acls); err != nil {
return nil, err
}
a := &ACLGuard{Config: config, Key: key}
a.ACL = acls.Entries
return a, nil
}
开发者ID:kevinawalsh,项目名称:cloudproxy,代码行数:31,代码来源:acl_guard.go
示例2: FixJobs
func (s *ApiServer) FixJobs() error {
log.Println("purging all jobs...")
prefix := store.TableJobFeed
_, err := store.ForwardTableScan(s.mdb, prefix, func(i int, k, v []byte) error {
job := &pb.FeedJob{}
if err := proto.Unmarshal(v, job); err != nil {
return err
}
if job.RemoteKey == "" {
return s.mdb.Delete(k)
}
return nil
})
if err != nil {
return err
}
prefix = store.TableJobRunning
_, err = store.ForwardTableScan(s.mdb, prefix, func(i int, k, v []byte) error {
job := &pb.FeedJob{}
if err := proto.Unmarshal(v, job); err != nil {
return err
}
if job.RemoteKey == "" {
return s.mdb.Delete(k)
}
return nil
})
if err != nil {
return err
}
return nil
}
开发者ID:hi-trust,项目名称:friendfeed,代码行数:35,代码来源:job.go
示例3: BreakOutBlockData
// BreakOutBlockData decomposes a blockData into its payloads and signatures.
// since a BlockData contains a slice of Envelopes, this functions returns slices of Payloads and Envelope.Signatures.
// the Payload/Signature pair has the same array index
func BreakOutBlockData(blockData *pb.BlockData) ([]*pb.Payload, [][]byte, error) {
var err error
var envelopeSignatures [][]byte
var payloads []*pb.Payload
var envelope *pb.Envelope
var payload *pb.Payload
for _, envelopeBytes := range blockData.Data {
envelope = &pb.Envelope{}
err = proto.Unmarshal(envelopeBytes, envelope)
if err != nil {
return nil, nil, err
}
payload = &pb.Payload{}
err = proto.Unmarshal(envelope.Payload, payload)
if err != nil {
return nil, nil, err
}
envelopeSignatures = append(envelopeSignatures, envelope.Signature)
payloads = append(payloads, payload)
}
return payloads, envelopeSignatures, nil
} // BreakOutBlockData
开发者ID:hyperledger,项目名称:fabric,代码行数:28,代码来源:configtxutils.go
示例4: block
func (d *Decoder) block() (*OSMPBF.BlobHeader, *OSMPBF.Blob, error) {
// BlobHeaderLength
headerSizeBuf := make([]byte, 4)
if _, err := io.ReadFull(d.r, headerSizeBuf); err != nil {
return nil, nil, err
}
headerSize := binary.BigEndian.Uint32(headerSizeBuf)
// BlobHeader
headerBuf := make([]byte, headerSize)
if _, err := io.ReadFull(d.r, headerBuf); err != nil {
return nil, nil, err
}
blobHeader := new(OSMPBF.BlobHeader)
if err := proto.Unmarshal(headerBuf, blobHeader); err != nil {
return nil, nil, err
}
// Blob
blobBuf := make([]byte, blobHeader.GetDatasize())
_, err := io.ReadFull(d.r, blobBuf)
if err != nil {
return nil, nil, err
}
blob := new(OSMPBF.Blob)
if err := proto.Unmarshal(blobBuf, blob); err != nil {
return nil, nil, err
}
return blobHeader, blob, nil
}
开发者ID:thomersch,项目名称:gosmparse,代码行数:30,代码来源:decoder.go
示例5: Apply
// Apply applies the rule to the given Envelope, replying with the Action to take for the message
func (cf *configFilter) Apply(message *cb.Envelope) (filter.Action, filter.Committer) {
msgData := &cb.Payload{}
err := proto.Unmarshal(message.Payload, msgData)
if err != nil {
return filter.Forward, nil
}
if msgData.Header == nil || msgData.Header.ChainHeader == nil || msgData.Header.ChainHeader.Type != int32(cb.HeaderType_CONFIGURATION_TRANSACTION) {
return filter.Forward, nil
}
config := &cb.ConfigurationEnvelope{}
err = proto.Unmarshal(msgData.Data, config)
if err != nil {
return filter.Reject, nil
}
err = cf.configManager.Validate(config)
if err != nil {
return filter.Reject, nil
}
return filter.Accept, &configCommitter{
manager: cf.configManager,
configEnvelope: config,
}
}
开发者ID:hyperledger,项目名称:fabric,代码行数:29,代码来源:filter.go
示例6: FixTooMuchJobs
func (s *ApiServer) FixTooMuchJobs() error {
log.Println("too much jobs: purging peridoc jobs...")
prefix := store.TableJobFeed
_, err := store.ForwardTableScan(s.mdb, prefix, func(i int, k, v []byte) error {
job := &pb.FeedJob{}
if err := proto.Unmarshal(v, job); err != nil {
return err
}
if int(job.MaxLimit) == 99 {
return s.mdb.Delete(k)
}
return nil
})
if err != nil {
return err
}
prefix = store.TableJobRunning
_, err = store.ForwardTableScan(s.mdb, prefix, func(i int, k, v []byte) error {
job := &pb.FeedJob{}
if err := proto.Unmarshal(v, job); err != nil {
return err
}
if int(job.MaxLimit) == 99 {
return s.mdb.Delete(k)
}
return nil
})
if err != nil {
return err
}
return nil
}
开发者ID:hi-trust,项目名称:friendfeed,代码行数:35,代码来源:job.go
示例7: updateReceiver
func updateReceiver(t *testing.T, resultch chan byte, errorch chan error, client ab.AtomicBroadcastClient) {
logger.Info("{Update Receiver} Creating a ledger update delivery stream.")
dstream, err := client.Deliver(context.Background())
if err != nil {
errorch <- fmt.Errorf("Failed to get Deliver stream: %s", err)
return
}
dstream.Send(&ab.DeliverUpdate{Type: &ab.DeliverUpdate_Seek{Seek: &ab.SeekInfo{Start: ab.SeekInfo_NEWEST, WindowSize: 10, ChainID: provisional.TestChainID}}})
logger.Info("{Update Receiver} Listening to ledger updates.")
for i := 0; i < 2; i++ {
m, inerr := dstream.Recv()
if inerr != nil {
errorch <- fmt.Errorf("Failed to receive consensus: %s", inerr)
return
}
b := m.Type.(*ab.DeliverResponse_Block)
logger.Info("{Update Receiver} Received a ledger update.")
for i, tx := range b.Block.Data.Data {
pl := &cb.Payload{}
e := &cb.Envelope{}
merr1 := proto.Unmarshal(tx, e)
merr2 := proto.Unmarshal(e.Payload, pl)
if merr1 == nil && merr2 == nil {
logger.Infof("{Update Receiver} %d - %v", i+1, pl.Data)
}
}
resultch <- UPDATE
}
logger.Info("{Update Receiver} Exiting...")
}
开发者ID:hyperledger,项目名称:fabric,代码行数:30,代码来源:sbft_test.go
示例8: DecryptProto
// Decrypts a proto using an AEAD. Unmarshals the result into dst. The result
// should only be considered written if this function returns true.
func DecryptProto(aead cipher.AEAD, msg string, additionalData []byte, dst proto.Message) bool {
msgBytes, err := base64.RawURLEncoding.DecodeString(msg)
if err != nil {
glog.V(2).Infof("Tried to decrypt proto with invalid base64: %v", err)
return false
}
var msgProto pb.EncryptedMessage
err = proto.Unmarshal(msgBytes, &msgProto)
if err != nil {
glog.V(2).Infof("Tried to decrypt proto with invalid pb.EncryptedMessage: %v", err)
return false
}
// Decrypt in-place.
plaintext := msgProto.Ciphertext
plaintext, err = aead.Open(plaintext[:0], msgProto.Nonce, msgProto.Ciphertext, additionalData)
if err != nil {
glog.V(2).Infof("Failed to decrypt data: %v", err)
return false
}
err = proto.Unmarshal(plaintext, dst)
if err != nil {
glog.V(2).Infof("Failed to decrypt proto: %v", err)
return false
}
return true
}
开发者ID:jonathanwei,项目名称:fproxy,代码行数:32,代码来源:crypto.go
示例9: decode
// Decodes a message byte buffer into a proto response, error code or nil
// Resulting object depends on response type.
func decode(buf []byte, resp proto.Message) (err error) {
var code uint8
var respbuf []byte
if len(buf) < 1 {
err = ErrInvalidResponseCode
return
}
code = buf[0]
if len(buf) > 1 {
respbuf = buf[1:]
} else {
respbuf = make([]byte, 0)
}
switch code {
case MsgRpbErrorResp:
errResp := &RpbErrorResp{}
if err = proto.Unmarshal(respbuf, errResp); err == nil {
err = errors.New(string(errResp.Errmsg))
}
case MsgRpbPingResp, MsgRpbSetClientIdResp, MsgRpbSetBucketResp, MsgRpbDelResp:
resp = nil
default:
err = proto.Unmarshal(respbuf, resp)
}
return
}
开发者ID:jcoene,项目名称:riago,代码行数:35,代码来源:message.go
示例10: Unboxing
func Unboxing(data []byte) (interface{}, error) {
if len(data) < 1 {
return nil, fmt.Errorf("warning: bad frame")
}
bagId := data[0]
data = data[1:]
switch bagId {
case BAG_ID_MSG:
if len(data) < 1 {
return nil, fmt.Errorf("warning: bad message frame")
}
upMsg := new(Msg)
if err := proto.Unmarshal(data, upMsg); err != nil {
return nil, fmt.Errorf("parse msg err %v", err)
}
return upMsg, nil
case BAG_ID_ACK:
ack := new(Ack)
if err := proto.Unmarshal(data, ack); err != nil {
return nil, fmt.Errorf("parse ack err %v", err)
}
return ack, nil
case BAG_ID_CMD:
cmd := new(Cmd)
if err := proto.Unmarshal(data, cmd); err != nil {
return nil, fmt.Errorf("parse cmd err %v", err)
}
return cmd, nil
default:
return nil, fmt.Errorf("warning: unknown bag id: %v", bagId)
}
}
开发者ID:philipbo,项目名称:kodec,代码行数:34,代码来源:kodec.go
示例11: UnmarshalKey
// UnmarshalKey deserializes a Verifier.
func UnmarshalKey(material []byte) (*Verifier, error) {
var ck CryptoKey
if err := proto.Unmarshal(material, &ck); err != nil {
return nil, err
}
if *ck.Version != CryptoVersion_CRYPTO_VERSION_1 {
return nil, newError("bad version")
}
if *ck.Purpose != CryptoKey_VERIFYING {
return nil, newError("bad purpose")
}
if *ck.Algorithm != CryptoKey_ECDSA_SHA {
return nil, newError("bad algorithm")
}
var ecvk ECDSA_SHA_VerifyingKeyV1
if err := proto.Unmarshal(ck.Key, &ecvk); err != nil {
return nil, err
}
ec, err := unmarshalECDSASHAVerifyingKeyV1(&ecvk)
if err != nil {
return nil, err
}
return &Verifier{ec}, nil
}
开发者ID:tmroeder,项目名称:cloudproxy,代码行数:31,代码来源:keys.go
示例12: Apply
func (scf *systemChainFilter) Apply(env *cb.Envelope) (filter.Action, filter.Committer) {
msgData := &cb.Payload{}
err := proto.Unmarshal(env.Payload, msgData)
if err != nil {
return filter.Forward, nil
}
if msgData.Header == nil || msgData.Header.ChainHeader == nil || msgData.Header.ChainHeader.Type != int32(cb.HeaderType_ORDERER_TRANSACTION) {
return filter.Forward, nil
}
configTx := &cb.Envelope{}
err = proto.Unmarshal(msgData.Data, configTx)
if err != nil {
return filter.Reject, nil
}
status := scf.cc.systemChain().authorizeAndInspect(configTx)
if status != cb.Status_SUCCESS {
return filter.Reject, nil
}
return filter.Accept, &systemChainCommitter{
cc: scf.cc,
configTx: configTx,
}
}
开发者ID:hyperledger,项目名称:fabric,代码行数:28,代码来源:systemchain.go
示例13: NewBackendAB
func NewBackendAB(backend *Backend) *BackendAB {
// XXX All the code below is a hacky shim until sbft can be adapter to the new multichain interface
it, _ := backend.ledger.Iterator(ab.SeekInfo_OLDEST, 0)
block, status := it.Next()
if status != cb.Status_SUCCESS {
panic("Error getting a block from the ledger")
}
env := &cb.Envelope{}
err := proto.Unmarshal(block.Data.Data[0], env)
if err != nil {
panic(err)
}
payload := &cb.Payload{}
err = proto.Unmarshal(env.Payload, payload)
if err != nil {
panic(err)
}
manager := &xxxSupportManager{
chainID: payload.Header.ChainHeader.ChainID,
support: &xxxSupport{reader: backend.ledger},
}
// XXX End hackiness
bab := &BackendAB{
backend: backend,
deliverserver: deliver.NewHandlerImpl(manager, 1000),
}
return bab
}
开发者ID:hyperledger,项目名称:fabric,代码行数:32,代码来源:backendab.go
示例14: 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
示例15: execute
// execute an opaque request which corresponds to an OBC Transaction
func (op *obcBatch) execute(seqNo uint64, raw []byte) {
reqs := &RequestBlock{}
if err := proto.Unmarshal(raw, reqs); err != nil {
logger.Warningf("Batch replica %d could not unmarshal request block: %s", op.pbft.id, err)
return
}
var txs []*pb.Transaction
for _, req := range reqs.Requests {
tx := &pb.Transaction{}
if err := proto.Unmarshal(req.Payload, tx); err != nil {
logger.Warningf("Batch replica %d could not unmarshal transaction: %s", op.pbft.id, err)
continue
}
logger.Debugf("Batch replica %d executing request with transaction %s from outstandingReqs, seqNo=%d", op.pbft.id, tx.Uuid, seqNo)
if outstanding, pending := op.reqStore.remove(req); !outstanding || !pending {
logger.Debugf("Batch replica %d missing transaction %s outstanding=%v, pending=%v", op.pbft.id, tx.Uuid, outstanding, pending)
}
txs = append(txs, tx)
op.deduplicator.Execute(req)
}
meta, _ := proto.Marshal(&Metadata{seqNo})
logger.Debugf("Batch replica %d received exec for seqNo %d containing %d transactions", op.pbft.id, seqNo, len(txs))
op.stack.Execute(meta, txs) // This executes in the background, we will receive an executedEvent once it completes
}
开发者ID:C0rWin,项目名称:fabric,代码行数:34,代码来源:batch.go
示例16: TestMsg
func TestMsg(t *testing.T) {
recMsg := &OSMsg{Fromu: proto.String("jack"), Tou: proto.String("tom"), Content: proto.String("first")}
b, err := proto.Marshal(recMsg)
if checkerr(err) {
return
}
buf := proto.NewBuffer(b)
err = proto.Unmarshal(b, &msg)
if checkerr(err) {
return
}
fmt.Println(msg)
fmt.Println(msg.String())
err = proto.Unmarshal(buf.Bytes(), &osmsg)
if checkerr(err) {
return
}
fmt.Println(osmsg)
fmt.Println(osmsg.String())
a := []int{1, 2}
a1 := a[:1]
fmt.Println(a, a1)
a1 = append(a1, 3)
fmt.Println(a, a1)
a1 = append(a1, 4)
fmt.Println(a, a1)
a1[1] = 10
fmt.Println(a, a1)
}
开发者ID:shaalx,项目名称:oschat,代码行数:33,代码来源:msg_test.go
示例17: execute
// execute an opaque request which corresponds to an OBC Transaction
func (op *obcBatch) execute(seqNo uint64, raw []byte) {
reqs := &RequestBlock{}
if err := proto.Unmarshal(raw, reqs); err != nil {
logger.Warningf("Batch replica %d could not unmarshal request block: %s", op.pbft.id, err)
return
}
logger.Debugf("Batch replica %d received exec for seqNo %d", op.pbft.id, seqNo)
var txs []*pb.Transaction
for _, req := range reqs.Requests {
tx := &pb.Transaction{}
if err := proto.Unmarshal(req.Payload, tx); err != nil {
logger.Warningf("Batch replica %d could not unmarshal transaction: %s", op.pbft.id, err)
continue
}
// TODO, this is a really and inefficient way to do this, but because reqs aren't comparable, they cannot be retrieved from the map directly
for oreq := range op.outstandingReqs {
if reflect.DeepEqual(oreq, req) {
delete(op.outstandingReqs, oreq)
break
}
}
txs = append(txs, tx)
}
meta, _ := proto.Marshal(&Metadata{seqNo})
op.stack.Execute(meta, txs) // This executes in the background, we will receive an executedEvent once it completes
}
开发者ID:yoshi-mori,项目名称:fabric,代码行数:33,代码来源:obc-batch.go
示例18: Unseal
// Unseal decrypts data that has been sealed by the Seal() operation, but only
// if the policy specified during the Seal() operation is satisfied.
func (tt *TPMTao) Unseal(sealed []byte) (data []byte, policy string, err error) {
// The sealed data is a HybridSealedData.
var h HybridSealedData
if err := proto.Unmarshal(sealed, &h); err != nil {
return nil, "", err
}
unsealed, err := tpm.Unseal(tt.tpmfile, h.SealedKey, tt.srkAuth[:])
if err != nil {
return nil, "", err
}
defer ZeroBytes(unsealed)
var ck CryptoKey
if err := proto.Unmarshal(unsealed, &ck); err != nil {
return nil, "", err
}
defer ZeroBytes(ck.Key)
crypter, err := UnmarshalCrypterProto(&ck)
if err != nil {
return nil, "", err
}
defer ZeroBytes(crypter.aesKey)
defer ZeroBytes(crypter.hmacKey)
m, err := crypter.Decrypt(h.EncryptedData)
if err != nil {
return nil, "", err
}
return m, SealPolicyDefault, nil
}
开发者ID:tmroeder,项目名称:cloudproxy,代码行数:35,代码来源:tpm_tao.go
示例19: DecodeToText
func (_ singleTaskDecoder) DecodeToText(data []byte) (string, error) {
var task single.Task
var profileExtension single.ProfileExtension
err := proto.Unmarshal(data, &task)
if err != nil {
return "", err
}
if task.Profile != nil && task.Profile.Extension != nil &&
task.Profile.Extension.TypeUrl ==
"type.googleapis.com/bacs.problem.single.ProfileExtension" {
ext := task.Profile.Extension
task.Profile = nil
err = proto.Unmarshal(ext.Value, &profileExtension)
if err != nil {
return "", err
}
}
text := proto.MarshalTextString(&task)
profileExtensionText := proto.MarshalTextString(&profileExtension)
if profileExtensionText != "" {
text += "\n"
text += profileExtensionText
}
return text, nil
}
开发者ID:bacsorg,项目名称:problems,代码行数:25,代码来源:single.go
示例20: OnEvent
func OnEvent(name string, msg []string) {
switch msg[0] {
case "BMATCHEDWIN":
fmt.Println("event: win")
params := &UrlParam{}
if err := proto.Unmarshal([]byte(msg[1]), params); err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("params:", params)
}
default:
event := msg[1]
switch event {
case "IMPRESSION":
case "CLICK":
case "CONVERSION":
default:
return
}
fmt.Println("event: ", event)
params := &UrlParam{}
if err := proto.Unmarshal([]byte(msg[2]), params); err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("params:", params)
}
}
}
开发者ID:yangzhao28,项目名称:rtb,代码行数:28,代码来源:main.go
注:本文中的github.com/golang/protobuf/proto.Unmarshal函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论