create.go 1.9 KB
Newer Older
Loïck Bonniot's avatar
Loïck Bonniot committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package sign

import (
	"crypto/sha512"
	"io/ioutil"
	"path/filepath"
	"time"

	"dfss/dfssc/common"
	"dfss/dfssc/security"
	"dfss/dfssp/api"
	"dfss/net"
	"golang.org/x/net/context"
)

// CreateManager handles the creation of a new contract.
type CreateManager struct {
18
19
20
21
22
23
	auth     *security.AuthContainer
	filepath string
	comment  string
	signers  []string
	hash     []byte
	filename string
Loïck Bonniot's avatar
Loïck Bonniot committed
24
25
}

26
27
// SendNewContract tries to create a contract on the platform and returns an error or nil
func SendNewContract(fileCA, fileCert, fileKey, addrPort, passphrase, filepath, comment string, signers []string) error {
Loïck Bonniot's avatar
Loïck Bonniot committed
28
	m := &CreateManager{
29
30
31
32
		auth:     security.NewAuthContainer(fileCA, fileCert, fileKey, addrPort, passphrase),
		filepath: filepath,
		comment:  comment,
		signers:  signers,
Loïck Bonniot's avatar
Loïck Bonniot committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
	}

	err := m.computeFile()
	if err != nil {
		return err
	}

	result, err := m.sendRequest()
	if err != nil {
		return err
	}

	return common.EvaluateErrorCodeResponse(result)
}

// computeFile computes hash and filename providing the contract filepath
func (m *CreateManager) computeFile() error {
	data, err := ioutil.ReadFile(m.filepath)
	if err != nil {
		return err
	}

	hash := sha512.Sum512(data)
56
	m.hash = hash[:]
Loïck Bonniot's avatar
Loïck Bonniot committed
57
58
59
60
61
62
63
64
	m.filename = filepath.Base(m.filepath)

	return nil
}

// sendRequest sends a new contract request for the platform and send it
func (m *CreateManager) sendRequest() (*api.ErrorCode, error) {

65
	ca, cert, key, err := m.auth.LoadFiles()
Loïck Bonniot's avatar
Loïck Bonniot committed
66
67
68
69
	if err != nil {
		return nil, err
	}

70
	conn, err := net.Connect(m.auth.AddrPort, cert, key, ca)
Loïck Bonniot's avatar
Loïck Bonniot committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
	if err != nil {
		return nil, err
	}

	request := &api.PostContractRequest{
		Hash:     m.hash,
		Filename: m.filename,
		Signer:   m.signers,
		Comment:  m.comment,
	}

	client := api.NewPlatformClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	response, err := client.PostContract(ctx, request)
	if err != nil {
		return nil, err
	}

	return response, nil
}