Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds the functionality to delete an election #118

Merged
merged 3 commits into from
May 10, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contracts/evoting/controller/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ func (a *RegisterAction) Execute(ctx node.Context) error {
router.HandleFunc("/evoting/elections/{electionID}", ep.Election).Methods("GET")
router.HandleFunc("/evoting/elections/{electionID}", ep.EditElection).Methods("PUT")
router.HandleFunc("/evoting/elections/{electionID}", eproxy.AllowCORS).Methods("OPTIONS")
router.HandleFunc("/evoting/elections/{electionID}", ep.DeleteElection).Methods("DELETE")
router.HandleFunc("/evoting/elections/{electionID}/vote", ep.NewElectionVote).Methods("POST")

router.NotFoundHandler = http.HandlerFunc(eproxy.NotFoundHandler)
Expand Down
56 changes: 56 additions & 0 deletions contracts/evoting/evoting.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions contracts/evoting/json/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package json

import (
"encoding/json"

"github.com/dedis/d-voting/contracts/evoting/types"
"go.dedis.ch/dela/serde"
"golang.org/x/xerrors"
Expand Down Expand Up @@ -111,6 +112,12 @@ func (transactionFormat) Encode(ctx serde.Context, msg serde.Message) ([]byte, e
}

m = TransactionJSON{CancelElection: &ce}
case types.DeleteElection:
de := DeleteElectionJSON{
ElectionID: t.ElectionID,
}

m = TransactionJSON{DeleteElection: &de}
default:
return nil, xerrors.Errorf("unknown type: '%T", msg)
}
Expand Down Expand Up @@ -178,6 +185,10 @@ func (transactionFormat) Decode(ctx serde.Context, data []byte) (serde.Message,
ElectionID: m.CancelElection.ElectionID,
UserID: m.CancelElection.UserID,
}, nil
case m.DeleteElection != nil:
return types.DeleteElection{
ElectionID: m.DeleteElection.ElectionID,
}, nil
}

return nil, xerrors.Errorf("empty type: %s", data)
Expand All @@ -194,6 +205,7 @@ type TransactionJSON struct {
RegisterPubShares *RegisterPubSharesJSON `json:",omitempty"`
CombineShares *CombineSharesJSON `json:",omitempty"`
CancelElection *CancelElectionJSON `json:",omitempty"`
DeleteElection *DeleteElectionJSON `json:",omitempty"`
}

// CreateElectionJSON is the JSON representation of a CreateElection transaction
Expand Down Expand Up @@ -251,6 +263,11 @@ type CancelElectionJSON struct {
UserID string
}

// DeleteElectionJSON is the JSON representation of a DeleteElection transaction
type DeleteElectionJSON struct {
ElectionID string
}

func decodeCastVote(ctx serde.Context, m CastVoteJSON) (serde.Message, error) {
factory := ctx.GetFactory(types.CiphervoteKey{})
if factory == nil {
Expand Down
10 changes: 10 additions & 0 deletions contracts/evoting/mod.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ type commands interface {
registerPubshares(snap store.Snapshot, step execution.Step) error
combineShares(snap store.Snapshot, step execution.Step) error
cancelElection(snap store.Snapshot, step execution.Step) error
deleteElection(snap store.Snapshot, step execution.Step) error
}

// Command defines a type of command for the value contract
Expand All @@ -72,12 +73,16 @@ const (
// CmdShuffleBallots is the command to shuffle ballots
CmdShuffleBallots Command = "SHUFFLE_BALLOTS"

// CmdRegisterPubShares is the command to register the pubshares
CmdRegisterPubShares Command = "REGISTER_PUB_SHARES"

// CmdCombineShares is the command to decrypt ballots
CmdCombineShares Command = "COMBINE_SHARES"
// CmdCancelElection is the command to cancel an election
CmdCancelElection Command = "CANCEL_ELECTION"

// CmdDelteElection is the command to delete an election
CmdDelteElection Command = "DELETE_ELECTION"
)

// NewCreds creates new credentials for a evoting contract execution. We might
Expand Down Expand Up @@ -200,6 +205,11 @@ func (c Contract) Execute(snap store.Snapshot, step execution.Step) error {
if err != nil {
return xerrors.Errorf("failed to cancel election: %v", err)
}
case CmdDelteElection:
err := c.cmd.deleteElection(snap, step)
if err != nil {
return xerrors.Errorf("failed to delete election: %v", err)
}
default:
return xerrors.Errorf("unknown command: %s", cmd)
}
Expand Down
4 changes: 4 additions & 0 deletions contracts/evoting/mod_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1346,6 +1346,10 @@ func (c fakeCmd) cancelElection(snap store.Snapshot, step execution.Step) error
return c.err
}

func (c fakeCmd) deleteElection(snap store.Snapshot, step execution.Step) error {
return c.err
}

func (c fakeCmd) registerPubshares(snap store.Snapshot, step execution.Step) error {
return c.err
}
Expand Down
40 changes: 34 additions & 6 deletions contracts/evoting/types/transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,20 @@ type ElectionsMetadata struct {
// ElectionIDs is a slice of hex-encoded election IDs
type ElectionIDs []string

// Contains checks if el is present
func (e ElectionIDs) Contains(el string) bool {
for _, e1 := range e {
// Contains checks if el is present. Return < 0 if not.
func (e ElectionIDs) Contains(el string) int {
for i, e1 := range e {
if e1 == el {
return true
return i
}
}

return false
return -1
}

// Add adds an election ID or returns an error if already present
func (e *ElectionIDs) Add(id string) error {
if e.Contains(id) {
if e.Contains(id) >= 0 {
return xerrors.Errorf("id %q already exist", id)
}

Expand All @@ -51,6 +51,14 @@ func (e *ElectionIDs) Add(id string) error {
return nil
}

// Remove removes an election ID from the list, if it exists
func (e *ElectionIDs) Remove(id string) {
i := e.Contains(id)
if i >= 0 {
*e = append((*e)[:i], (*e)[i+1:]...)
}
}

// TransactionFactory provides the mean to deserialize a transaction.
//
// - implements serde.Factory
Expand Down Expand Up @@ -267,6 +275,26 @@ func (ce CancelElection) Serialize(ctx serde.Context) ([]byte, error) {
return data, nil
}

// DeleteElection defines the transaction to delete the election
//
// - implements serde.Message
type DeleteElection struct {
// ElectionID is hex-encoded
ElectionID string
}

// Serialize implements serde.Message
func (ce DeleteElection) Serialize(ctx serde.Context) ([]byte, error) {
format := transactionFormats.Get(ctx.GetFormat())

data, err := format.Encode(ctx, ce)
if err != nil {
return nil, xerrors.Errorf("failed to encode cancel election: %v", err)
}

return data, nil
}

// RandomID returns the hex encoding of a randomly created 32 byte ID.
func RandomID() (string, error) {
buf := make([]byte, 32)
Expand Down
26 changes: 26 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ SC6:CombineShares
SC2:ElectionGetInfo



```

In case of error:
Expand Down Expand Up @@ -267,6 +269,30 @@ Return:

```

# SC?: Election delete

| | |
| ------- | --------------------------------- |
| URL | `/evoting/elections/{ElectionID}` |
| Method | `DELETE` |
| Input | |
| Headers | {Authorization: <token>} |

The <token> value must be the hex-encoded signature on the hex-encoded
electionID:

```
<token> = hex( sig( hex( electionID ) ) )
```

Return:

`200 OK` `text/plain`

```

```

# SC?: Election get all infos

| | |
Expand Down
65 changes: 63 additions & 2 deletions proxy/election.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"go.dedis.ch/dela/core/txn/pool"
"go.dedis.ch/dela/serde"
"go.dedis.ch/kyber/v3"
"go.dedis.ch/kyber/v3/sign/schnorr"
"golang.org/x/xerrors"
)

Expand Down Expand Up @@ -147,7 +148,7 @@ func (h *election) NewElectionVote(w http.ResponseWriter, r *http.Request) {
return
}

if !elecMD.ElectionsIDs.Contains(electionID) {
if elecMD.ElectionsIDs.Contains(electionID) < 0 {
http.Error(w, "the election does not exist", http.StatusNotFound)
return
}
Expand Down Expand Up @@ -214,7 +215,7 @@ func (h *election) EditElection(w http.ResponseWriter, r *http.Request) {
return
}

if !elecMD.ElectionsIDs.Contains(electionID) {
if elecMD.ElectionsIDs.Contains(electionID) < 0 {
http.Error(w, "the election does not exist", http.StatusNotFound)
return
}
Expand Down Expand Up @@ -453,6 +454,61 @@ func (h *election) Elections(w http.ResponseWriter, r *http.Request) {
}
}

// DeleteElection implements proxy.Proxy
func (h *election) DeleteElection(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)

if vars == nil || vars["electionID"] == "" {
http.Error(w, fmt.Sprintf("electionID not found: %v", vars), http.StatusInternalServerError)
return
}

electionID := vars["electionID"]

elecMD, err := h.getElectionsMetadata()
if err != nil {
http.Error(w, "failed to get election metadata", http.StatusNotFound)
return
}

if elecMD.ElectionsIDs.Contains(electionID) < 0 {
http.Error(w, "the election does not exist", http.StatusNotFound)
return
}

// auth should contain the hex-encoded signature on the hex-encoded election
// ID
auth := r.Header.Get("Authorization")

sig, err := hex.DecodeString(auth)
if err != nil {
BadRequestError(w, r, xerrors.Errorf("failed to decode auth: %v", err), nil)
return
}

err = schnorr.Verify(suite, h.pk, []byte(electionID), sig)
if err != nil {
ForbiddenError(w, r, xerrors.Errorf("signature verification failed: %v", err), nil)
return
}

deleteElection := types.DeleteElection{
ElectionID: electionID,
}

data, err := deleteElection.Serialize(h.context)
if err != nil {
InternalError(w, r, xerrors.Errorf("failed to marshal DeleteElection: %v", err), nil)
return
}

_, err = h.submitAndWaitForTxn(r.Context(), evoting.CmdDelteElection, evoting.ElectionArg, data)
if err != nil {
http.Error(w, "failed to submit txn: "+err.Error(), http.StatusInternalServerError)
return
}
}

// waitForTxnID blocks until `ID` is included or `events` is closed.
func (h *election) waitForTxnID(events <-chan ordering.Event, ID []byte) error {
for event := range events {
Expand Down Expand Up @@ -483,6 +539,11 @@ func (h *election) getElectionsMetadata() (types.ElectionsMetadata, error) {
return md, nil
}

// if there is not election created yet the metadata will be empty
if len(proof.GetValue()) == 0 {
return types.ElectionsMetadata{}, nil
}

err = json.Unmarshal(proof.GetValue(), &md)
if err != nil {
return md, xerrors.Errorf("failed to unmarshal ElectionMetadata: %v", err)
Expand Down
Loading