persist.go 1.94 KB
Newer Older
1 2 3 4 5 6 7 8
package sign

import (
	"encoding/json"
	"fmt"
	"io/ioutil"

	cAPI "dfss/dfssc/api"
Caro Axel's avatar
Caro Axel committed
9
	"dfss/dfssc/common"
10 11 12
	"dfss/dfssp/contract"
)

13
// SignedContractJSON is an union of contract and related signatures
14 15 16 17 18 19 20 21 22
type SignedContractJSON struct {
	Contract   contract.JSON
	Signatures []cAPI.Signature
}

// PersistSignaturesToFile save contract informations and signatures to disk
func (m *SignatureManager) PersistSignaturesToFile() error {

	// Check content, don't write an empty file
23
	if len(m.archives.receivedSignatures) == 0 {
24 25 26 27 28 29 30 31
		return fmt.Errorf("No stored signatures, cannot create an empty file (yes I'm a coward)")
	}

	// Fill JSON struct
	signedContract := SignedContractJSON{
		Contract: *m.contract,
		Signatures: make(
			[]cAPI.Signature,
32
			len(m.archives.sentSignatures)+len(m.archives.receivedSignatures),
33 34 35 36 37 38 39
		),
	}

	for i, s := range m.archives.sentSignatures {
		signedContract.Signatures[i] = *s
	}

40
	for i, s := range m.archives.receivedSignatures {
41 42 43
		signedContract.Signatures[len(m.archives.sentSignatures)+i] = *s
	}

44
	proof, err := json.MarshalIndent(signedContract, "", "  ")
45 46 47 48
	if err != nil {
		return err
	}

Caro Axel's avatar
Caro Axel committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
	return ioutil.WriteFile(m.mail+"-"+m.uuid+".proof", proof, 0600)
}

// PersistRecoverDataToFile : save recover informations to disk.
// returns the file name and an error if any occured
func (m *SignatureManager) PersistRecoverDataToFile() (string, error) {
	// Check content, don't write an empty file
	if len(m.uuid) == 0 || len(m.ttpData.Addrport) == 0 || len(m.ttpData.Hash) == 0 {
		return "", fmt.Errorf("Invalid recover data. Cannot persist file.")
	}

	// Fill JSON struct
	recData := common.RecoverDataJSON{
		SignatureUUID: m.uuid,
		TTPAddrport:   m.ttpData.Addrport,
		TTPHash:       m.ttpData.Hash,
	}

	file, err := json.MarshalIndent(recData, "", "  ")
	if err != nil {
		return "", err
	}

	filename := m.mail + "-" + m.uuid + ".run"
	err = ioutil.WriteFile(filename, file, 0600)
	if err != nil {
		return "", err
	}

	return filename, nil
79
}