create.go 1.88 KB
Newer Older
Loïck Bonniot's avatar
Loïck Bonniot committed
1 2 3 4 5 6 7 8 9 10 11
package sign

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

	"dfss/dfssc/common"
	"dfss/dfssc/security"
	"dfss/dfssp/api"
	"dfss/net"
12
	"github.com/spf13/viper"
Loïck Bonniot's avatar
Loïck Bonniot committed
13 14 15 16 17
	"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
// SendNewContract tries to create a contract on the platform and returns an error or nil
ElyKar's avatar
ElyKar committed
27
func SendNewContract(passphrase, filepath, comment string, signers []string) error {
Loïck Bonniot's avatar
Loïck Bonniot committed
28
	m := &CreateManager{
ElyKar's avatar
ElyKar committed
29
		auth:     security.NewAuthContainer(passphrase),
30 31 32
		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(viper.GetString("platform_addrport"), cert, key, ca, nil)
Loïck Bonniot's avatar
Loïck Bonniot committed
71 72 73 74 75 76 77 78 79 80 81 82
	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)
83
	ctx, cancel := context.WithTimeout(context.Background(), net.DefaultTimeout)
Loïck Bonniot's avatar
Loïck Bonniot committed
84 85 86 87 88 89 90 91
	defer cancel()
	response, err := client.PostContract(ctx, request)
	if err != nil {
		return nil, err
	}

	return response, nil
}