github.com/braveheart12/just@v0.8.7/messagebus/parcel.go (about)

     1  /*
     2   *    Copyright 2019 Insolar Technologies
     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 messagebus
    18  
    19  import (
    20  	"context"
    21  	"crypto"
    22  
    23  	"github.com/insolar/insolar/core"
    24  	"github.com/insolar/insolar/core/message"
    25  	"github.com/insolar/insolar/instrumentation/inslogger"
    26  	"github.com/insolar/insolar/instrumentation/instracer"
    27  	"github.com/pkg/errors"
    28  )
    29  
    30  type parcelFactory struct {
    31  	DelegationTokenFactory     core.DelegationTokenFactory     `inject:""`
    32  	PlatformCryptographyScheme core.PlatformCryptographyScheme `inject:""`
    33  	Cryptography               core.CryptographyService        `inject:""`
    34  }
    35  
    36  // NewParcelFactory returns new instance of parcelFactory
    37  func NewParcelFactory() message.ParcelFactory {
    38  	return &parcelFactory{}
    39  }
    40  
    41  func (pf *parcelFactory) Create(ctx context.Context, msg core.Message, sender core.RecordRef, token core.DelegationToken, currentPulse core.Pulse) (core.Parcel, error) {
    42  	if msg == nil {
    43  		return nil, errors.New("failed to signature a nil message")
    44  	}
    45  
    46  	serialized := message.ToBytes(msg)
    47  	signature, err := pf.Cryptography.Sign(serialized)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	return &message.Parcel{
    53  		Msg:           msg,
    54  		Signature:     signature.Bytes(),
    55  		LogTraceID:    inslogger.TraceID(ctx),
    56  		TraceSpanData: instracer.MustSerialize(ctx),
    57  		Sender:        sender,
    58  		Token:         token,
    59  		PulseNumber:   currentPulse.PulseNumber,
    60  	}, nil
    61  }
    62  
    63  func (pf *parcelFactory) Validate(publicKey crypto.PublicKey, parcel core.Parcel) error {
    64  	ok := pf.Cryptography.Verify(publicKey, core.SignatureFromBytes(parcel.GetSign()), message.ToBytes(parcel.Message()))
    65  	if !ok {
    66  		return errors.New("parcel isn't valid")
    67  	}
    68  	return nil
    69  }