starter.go 5.94 KB
Newer Older
1
2
3
4
5
package sign

import (
	"errors"
	"fmt"
6
	"log"
7
	"strconv"
Loïck Bonniot's avatar
Loïck Bonniot committed
8
	"time"
9

Caro Axel's avatar
Caro Axel committed
10
11
	"dfss"
	cAPI "dfss/dfssc/api"
12
	"dfss/dfssc/common"
13
	"dfss/dfssc/security"
Caro Axel's avatar
Caro Axel committed
14
	pAPI "dfss/dfssp/api"
15
16
17
	"dfss/dfssp/contract"
	"dfss/net"
	"golang.org/x/net/context"
Caro Axel's avatar
Caro Axel committed
18
	"google.golang.org/grpc"
19
20
21
22
)

// SignatureManager handles the signature of a contract.
type SignatureManager struct {
23
24
25
26
27
28
29
30
31
32
33
34
35
	auth         *security.AuthContainer
	localPort    int
	contract     *contract.JSON // contains the contractUUID, the list of the signers' hashes, the hash of the contract
	platform     pAPI.PlatformClient
	peers        map[string]*cAPI.ClientClient
	nbReady      int
	cServer      *grpc.Server
	sequence     []uint32
	currentIndex int
	uuid         string
	keyHash      [][]byte
	mail         string
	archives     *Archives
36
37
38
39
40
41
42
43
}

// Archives stores the recieved and sent messages, as evidence if needed
type Archives struct {
	sentPromises       []*cAPI.Promise
	recievedPromises   []*cAPI.Promise
	sentSignatures     []*cAPI.Signature
	recievedSignatures []*cAPI.Signature
44
45
46
47
48
49
50
51
}

// NewSignatureManager populates a SignatureManager and connects to the platform.
func NewSignatureManager(fileCA, fileCert, fileKey, addrPort, passphrase string, port int, c *contract.JSON) (*SignatureManager, error) {
	m := &SignatureManager{
		auth:      security.NewAuthContainer(fileCA, fileCert, fileKey, addrPort, passphrase),
		localPort: port,
		contract:  c,
52
53
54
55
56
57
		archives: &Archives{
			sentPromises:       make([]*cAPI.Promise, 0),
			recievedPromises:   make([]*cAPI.Promise, 0),
			sentSignatures:     make([]*cAPI.Signature, 0),
			recievedSignatures: make([]*cAPI.Signature, 0),
		},
58
	}
Caro Axel's avatar
Caro Axel committed
59
	var err error
60
	_, _, _, err = m.auth.LoadFiles()
61
62
63
64
	if err != nil {
		return nil, err
	}

65
	m.mail = m.auth.Cert.Subject.CommonName
66

Caro Axel's avatar
Caro Axel committed
67
	m.cServer = m.GetServer()
68
	go func() { log.Fatalln(net.Listen("0.0.0.0:"+strconv.Itoa(port), m.cServer)) }()
Caro Axel's avatar
Caro Axel committed
69

70
	conn, err := net.Connect(m.auth.AddrPort, m.auth.Cert, m.auth.Key, m.auth.CA)
71
72
73
74
	if err != nil {
		return nil, err
	}

Caro Axel's avatar
Caro Axel committed
75
	m.platform = pAPI.NewPlatformClient(conn)
76

Caro Axel's avatar
Caro Axel committed
77
	m.peers = make(map[string]*cAPI.ClientClient)
78
	for _, u := range c.Signers {
79
		if u.Email != m.auth.Cert.Subject.CommonName {
80
81
			m.peers[u.Email] = nil
		}
82
83
84
85
86
87
88
	}

	return m, nil
}

// ConnectToPeers tries to fetch the list of users for this contract, and tries to establish a connection to each peer.
func (m *SignatureManager) ConnectToPeers() error {
Caro Axel's avatar
Caro Axel committed
89
	stream, err := m.platform.JoinSignature(context.Background(), &pAPI.JoinSignatureRequest{
90
91
92
93
94
95
96
97
98
99
100
101
102
		ContractUuid: m.contract.UUID,
		Port:         uint32(m.localPort),
	})
	if err != nil {
		return err
	}

	for {
		userConnected, err := stream.Recv()
		if err != nil {
			return err
		}
		errorCode := userConnected.GetErrorCode()
Caro Axel's avatar
Caro Axel committed
103
		if errorCode.Code != pAPI.ErrorCode_SUCCESS {
104
105
106
107
			return errors.New(errorCode.Message)
		}
		ready, err := m.addPeer(userConnected.User)
		if err != nil {
108
			continue // Unable to connect to this user, ignore it for the moment
109
110
111
112
113
114
115
116
117
118
		}
		if ready {
			break
		}
	}

	return nil
}

// addPeer stores a peer from the platform and tries to establish a connection to this peer.
Caro Axel's avatar
Caro Axel committed
119
func (m *SignatureManager) addPeer(user *pAPI.User) (ready bool, err error) {
120
121
122
123
	if user == nil {
		err = errors.New("unexpected user format")
		return
	}
124
125
126
	if _, ok := m.peers[user.Email]; !ok {
		return // Ignore if unknown
	}
127

Caro Axel's avatar
Caro Axel committed
128
	addrPort := user.Ip + ":" + strconv.Itoa(int(user.Port))
129
	fmt.Println("- Trying to connect with", user.Email, "/", addrPort)
130

131
	conn, err := net.Connect(addrPort, m.auth.Cert, m.auth.Key, m.auth.CA)
Caro Axel's avatar
Caro Axel committed
132
133
134
135
136
137
	if err != nil {
		return false, err
	}

	// Sending Hello message
	client := cAPI.NewClientClient(conn)
138
	lastConnection := m.peers[user.Email]
Caro Axel's avatar
Caro Axel committed
139
	m.peers[user.Email] = &client
140
141
142
143

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	msg, err := client.Discover(ctx, &cAPI.Hello{Version: dfss.Version})
Caro Axel's avatar
Caro Axel committed
144
145
146
	if err != nil {
		return false, err
	}
147

Caro Axel's avatar
Caro Axel committed
148
	// Printing answer: application version
149
150
	// TODO check certificate
	fmt.Println("  Successfully connected!", "[", msg.Version, "]")
151
152

	// Check if we have any other peer to connect to
153
154
155
156
	if lastConnection == nil {
		m.nbReady++
		if m.nbReady == len(m.contract.Signers)-1 {
			return true, nil
157
158
159
		}
	}

160
	return false, nil
161
}
Loïck Bonniot's avatar
Loïck Bonniot committed
162
163
164

// SendReadySign sends the READY signal to the platform, and wait (potentially a long time) for START signal.
func (m *SignatureManager) SendReadySign() (signatureUUID string, err error) {
165
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
Loïck Bonniot's avatar
Loïck Bonniot committed
166
	defer cancel()
Loïck Bonniot's avatar
Loïck Bonniot committed
167
	launch, err := m.platform.ReadySign(ctx, &pAPI.ReadySignRequest{
Loïck Bonniot's avatar
Loïck Bonniot committed
168
169
170
171
172
173
174
		ContractUuid: m.contract.UUID,
	})
	if err != nil {
		return
	}

	errorCode := launch.GetErrorCode()
Loïck Bonniot's avatar
Loïck Bonniot committed
175
	if errorCode.Code != pAPI.ErrorCode_SUCCESS {
Loïck Bonniot's avatar
Loïck Bonniot committed
176
177
178
179
		err = errors.New(errorCode.Code.String() + " " + errorCode.Message)
		return
	}

180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
	// Check signers from platform data
	if len(m.contract.Signers) != len(launch.KeyHash) {
		err = errors.New("Corrupted DFSS file: bad number of signers, unable to sign safely")
		return
	}

	for i, s := range m.contract.Signers {
		if s.Hash != fmt.Sprintf("%x", launch.KeyHash[i]) {
			err = errors.New("Corrupted DFSS file: signer " + s.Email + " has an invalid hash, unable to sign safely")
			return
		}
	}

	m.sequence = launch.Sequence
	m.uuid = launch.SignatureUuid
195
	m.keyHash = launch.KeyHash
196
	signatureUUID = m.uuid
Loïck Bonniot's avatar
Loïck Bonniot committed
197
198
	return
}
199

200
// Initialize computes the values needed for the start of the signing
201
func (m *SignatureManager) Initialize() (uint32, int, error) {
202
203
	myID, err := m.FindID()
	if err != nil {
204
		return 0, 0, err
205
206
	}

207
	m.currentIndex, err = common.FindNextIndex(m.sequence, myID, -1)
208
	if err != nil {
209
		return 0, 0, err
210
211
	}

212
	nextIndex, err := common.FindNextIndex(m.sequence, myID, m.currentIndex)
213
	if err != nil {
214
		return 0, 0, err
215
216
	}

217
	return myID, nextIndex, nil
218
219
220
221
}

// FindID finds the sequence id for the user's email and the contract to sign
func (m *SignatureManager) FindID() (uint32, error) {
222
223
	signers := m.contract.Signers
	for id, signer := range signers {
224
		if signer.Email == m.mail {
225
226
227
228
229
			return uint32(id), nil
		}
	}
	return 0, errors.New("Mail couldn't be found amongst signers")
}