promises.go 2.38 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
package sign

import (
	"errors"
	"time"

	cAPI "dfss/dfssc/api"
	dAPI "dfss/dfssd/api"
	pAPI "dfss/dfssp/api"
	"golang.org/x/net/context"
)

13
func (m *SignatureManager) createContext(from, to uint32) (*cAPI.Context, error) {
14
	if int(from) >= len(m.keyHash) || int(to) >= len(m.keyHash) {
15
		return nil, errors.New("Invalid id for context creation")
16
	}
17
	return &cAPI.Context{
18 19
		RecipientKeyHash:     m.keyHash[to],
		SenderKeyHash:        m.keyHash[from],
Caro Axel's avatar
Caro Axel committed
20 21 22 23
		Sequence:             m.sequence,
		Signers:              m.keyHash,
		ContractDocumentHash: []byte(m.contract.File.Hash),
		SignatureUUID:        m.uuid,
24
	}, nil
25 26
}

27 28 29 30
// CreatePromise creates a promise from 'from' to 'to', in the context of the SignatureManager
// provided the specified sequence indexes are valid
func (m *SignatureManager) CreatePromise(from, to uint32) (*cAPI.Promise, error) {
	context, err := m.createContext(from, to)
31
	if err != nil {
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
		return nil, err
	}

	if m.currentIndex < 0 {
		return nil, errors.New("Invalid currentIndex for promise creation")
	}

	return &cAPI.Promise{
		Index:   uint32(m.currentIndex),
		Context: context,
		Payload: []byte{0x41},
	}, nil
}

// SendEvidence factorizes the send code between promises and signatures.
// You can use it by setting either promise or signature to `nil`.
// The successfully sent evidence is then added to the archives.
func (m *SignatureManager) SendEvidence(promise *cAPI.Promise, signature *cAPI.Signature, to uint32) (err error) {
	connection, mail := m.GetClient(to)
	if connection == nil {
		return
53 54 55 56 57
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

58 59 60 61 62 63 64
	var result *pAPI.ErrorCode
	if promise != nil {
		result, err = (*connection).TreatPromise(ctx, promise)
	} else if signature != nil {
		result, err = (*connection).TreatSignature(ctx, signature)
	} else {
		err = errors.New("both promise and signature are nil, cannot send anything")
65 66
	}

67 68 69 70 71 72 73 74 75 76 77 78 79 80
	if err == nil && result != nil && result.Code == pAPI.ErrorCode_SUCCESS {
		m.archives.mutex.Lock()
		if promise != nil {
			dAPI.DLog("sent promise to " + mail)
			m.archives.sentPromises = append(m.archives.sentPromises, promise)
		} else {
			dAPI.DLog("sent signature to " + mail)
			m.archives.sentSignatures = append(m.archives.sentSignatures, signature)
		}
		m.archives.mutex.Unlock()
	} else {
		dAPI.DLog("unable to send evidence to " + mail)
		err = errors.New("received wrong error code")
	}
81

82
	return
83
}