summaryrefslogtreecommitdiff
path: root/entity/operation.go
blob: 0cc89f1a69e1f238d53a462ec1a84f682cc1d332 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
This file is part of Dscuss.
Copyright (C) 2018  Vitaly Minko

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package entity

import (
	"encoding/json"
	"fmt"
	"time"
	"vminko.org/dscuss/crypto"
	"vminko.org/dscuss/errors"
	"vminko.org/dscuss/log"
)

type OperationType int
type OperationReason int

const (
	OperationTypeRemoveMessage OperationType = iota
	OperationTypeBanUser
	// TBD: OperationTypeBanUserTemporarily
	// TBD: OperationTypeEditMessageTopic
	// TBD: OperationTypeEditMessageSubject
	// TBD: OperationTypeEditMessageText
)

const (
	OperationTypeRemoveMessageStr string = "RemoveMessage"
	OperationTypeBanUserStr       string = "BanUser"
)

const (
	OperationReasonProtocolViolation OperationReason = iota
	OperationReasonSpam
	OperationReasonOfftopic
	OperationReasonAbuse
	OperationReasonDuplicate
)

const (
	OperationReasonProtocolViolationStr string = "ProtocolViolation"
	OperationReasonSpamStr              string = "SPAM"
	OperationReasonOfftopicStr          string = "Offtopic"
	OperationReasonAbuseStr             string = "Abuse"
	OperationReasonDuplicateStr         string = "Duplicate"
)

const (
	MaxOperationCommentLen int = 1024
	MinOperationPostDelay      = 1 * time.Minute
)

var lastOperTimestamp time.Time

// Operation is an action performed on a user or a message.
type Operation struct {
	UnsignedOperation
	Sig crypto.Signature
}

type UnsignedOperation struct {
	Descriptor
	OperationContent
}

type OperationContent struct {
	Type          OperationType
	Reason        OperationReason
	Comment       string
	AuthorID      ID
	ObjectID      ID
	DatePerformed time.Time
}

type StoredOperation struct {
	O      *Operation
	Stored time.Time
}

func (ot OperationType) String() string {
	switch ot {
	case OperationTypeRemoveMessage:
		return OperationTypeRemoveMessageStr
	case OperationTypeBanUser:
		return OperationTypeBanUserStr
	default:
		return "unknown operation type"
	}
}

func (or OperationReason) String() string {
	switch or {
	case OperationReasonProtocolViolation:
		return OperationReasonProtocolViolationStr
	case OperationReasonSpam:
		return OperationReasonSpamStr
	case OperationReasonOfftopic:
		return OperationReasonOfftopicStr
	case OperationReasonAbuse:
		return OperationReasonAbuseStr
	case OperationReasonDuplicate:
		return OperationReasonDuplicateStr
	default:
		return "unknown operation reason"
	}
}

func (or *OperationReason) ParseString(s string) error {
	switch s {
	case OperationReasonProtocolViolationStr:
		*or = OperationReasonProtocolViolation
	case OperationReasonSpamStr:
		*or = OperationReasonSpam
	case OperationReasonOfftopicStr:
		*or = OperationReasonOfftopic
	case OperationReasonAbuseStr:
		*or = OperationReasonAbuse
	case OperationReasonDuplicateStr:
		*or = OperationReasonDuplicate
	default:
		return errors.Parsing
	}
	return nil
}

func (uo *UnsignedOperation) ShortID() string {
	return uo.Descriptor.ID.Shorten()
}

func (uo *UnsignedOperation) OperationType() OperationType {
	return uo.OperationContent.Type
}

func (uo *UnsignedOperation) Type() Type {
	return uo.Descriptor.Type
}

func (uo *UnsignedOperation) ID() *ID {
	return &uo.Descriptor.ID
}

func (uo *UnsignedOperation) String() string {
	return fmt.Sprintf("%s (%s performed oper type %s reason %s on %s)",
		uo.ShortID(), uo.AuthorID.Shorten(), uo.OperationType().String(),
		uo.Reason, uo.ObjectID.Shorten())
}

func (uo *UnsignedOperation) isValid() bool {
	correctID := uo.OperationContent.ToID()
	if uo.Descriptor.ID != *correctID {
		log.Debugf("Operation %s has invalid ID", uo)
		return false
	}
	t := uo.OperationContent.Type
	if t != OperationTypeRemoveMessage && t != OperationTypeBanUser {
		log.Debugf("Operation %s has invalid type %d", uo, t)
		return false
	}
	isReasonOK := uo.Reason == OperationReasonSpam || uo.Reason == OperationReasonOfftopic ||
		uo.Reason == OperationReasonAbuse || uo.Reason == OperationReasonDuplicate ||
		uo.Reason == OperationReasonProtocolViolation
	if !isReasonOK {
		log.Debugf("Operation %s has invalid reason %d", uo, uo.Reason)
		return false
	}
	if uo.AuthorID.IsZero() {
		log.Debugf("Operation %s has empty author", uo, uo.AuthorID)
		return false
	}
	if uo.ObjectID.IsZero() {
		log.Debugf("Operation %s has empty objectr", uo, uo.ObjectID)
		return false
	}
	return true
}

func (o *Operation) IsUnsignedPartValid() bool {
	return o.UnsignedOperation.isValid()
}

func (o *Operation) IsSigValid(pubKey *crypto.PublicKey) bool {
	jop, err := json.Marshal(&o.UnsignedOperation)
	if err != nil {
		log.Fatal("Can't marshal UnsignedOperation: " + err.Error())
	}
	res := pubKey.Verify(jop, o.Sig)
	if !res {
		log.Debugf("Operation %s has invalid signature", o)
	}
	return res
}

func (o *Operation) IsValid(pubKey *crypto.PublicKey) bool {
	return o.IsUnsignedPartValid() && o.IsSigValid(pubKey)
}

// EmergeOperation creates a new operation. It will be called when owner wants to
// perform a new operation and automatically by the protocol implementation (for
// example, for blocking malicious peers).
// Signature will be created using the provided signer.
func EmergeOperation(
	typ OperationType,
	reason OperationReason,
	comment string,
	authorID *ID,
	objectID *ID,
	signer *crypto.Signer,
) (*Operation, error) {
	if time.Since(lastOperTimestamp) < MinOperationPostDelay {
		log.Errorf("Attempt to create an operation violating the limit of the operation post rate")
		return nil, errors.OperPostRateErr
	} else {
		lastOperTimestamp = time.Now()
	}
	uo := newUnsignedOperation(typ, reason, comment, authorID, objectID, time.Now())
	if !uo.isValid() {
		return nil, errors.WrongArguments
	}
	joper, err := json.Marshal(uo)
	if err != nil {
		log.Fatal("Can't marshal unsigned Operation: " + err.Error())
	}
	sig, err := signer.Sign(joper)
	if err != nil {
		log.Fatal("Can't sign JSON-encoded Operation entity: " + err.Error())
	}
	return &Operation{UnsignedOperation: *uo, Sig: sig}, nil
}

// NewOperation composes a new operation entity object from the specified data.
func NewOperation(
	typ OperationType,
	reason OperationReason,
	comment string,
	authorID *ID,
	objectID *ID,
	datePerformed time.Time,
	sig crypto.Signature,
) (*Operation, error) {
	uo := newUnsignedOperation(typ, reason, comment, authorID, objectID, datePerformed)
	if !uo.isValid() {
		return nil, errors.WrongArguments
	}
	return &Operation{UnsignedOperation: *uo, Sig: sig}, nil
}

func newOperationContent(
	typ OperationType,
	reason OperationReason,
	comment string,
	authorID *ID,
	objectID *ID,
	datePerformed time.Time,
) *OperationContent {
	return &OperationContent{
		Type:          typ,
		Reason:        reason,
		Comment:       comment,
		AuthorID:      *authorID,
		ObjectID:      *objectID,
		DatePerformed: datePerformed,
	}
}

func (oc *OperationContent) ToID() *ID {
	joc, err := json.Marshal(oc)
	if err != nil {
		log.Fatal("Can't marshal OperationContent: " + err.Error())
	}
	id := NewID(joc)
	return &id
}

func newUnsignedOperation(
	typ OperationType,
	reason OperationReason,
	comment string,
	authorID *ID,
	objectID *ID,
	datePerformed time.Time,
) *UnsignedOperation {
	oc := newOperationContent(typ, reason, comment, authorID, objectID, datePerformed)
	return &UnsignedOperation{
		Descriptor: Descriptor{
			Type: TypeOperation,
			ID:   *oc.ToID(),
		},
		OperationContent: *oc,
	}
}