revocation_db.go 5.99 KB
Newer Older
1
2
3
4
5
6
7
8
9
package irma

import (
	"fmt"
	"log"
	"sync"

	"github.com/go-errors/errors"
	"github.com/jinzhu/gorm"
10
	"github.com/privacybydesign/gabi/revocation"
11
12
13
14
15
16
17
18
19
20
21
22
23
	"github.com/sirupsen/logrus"
)

type (
	revStorage interface {
		// Transaction executes the given closure within a transaction.
		Transaction(f func(tx revStorage) error) (err error)
		// Get deserializes into o the record satisfying col = key.
		Get(typ CredentialTypeIdentifier, col string, key interface{}, o interface{}) error
		// Insert a new record which must not yet exist.
		Insert(o interface{}) error
		// Save an existing record.
		Save(o interface{}) error
24
		Upsert(o interface{}) error
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
		// Last deserializes the last record into o.
		Last(typ CredentialTypeIdentifier, o interface{}) error
		// Exists checks whether records exist satisfying col = key.
		Exists(typ CredentialTypeIdentifier, col string, key interface{}, o interface{}) (bool, error)
		// HasRecords checks whether any records exist for the given type.
		HasRecords(typ CredentialTypeIdentifier, o interface{}) (bool, error)
		// From deserializes into o all records where col >= key.
		From(typ CredentialTypeIdentifier, col string, key interface{}, o interface{}) error
		// Latest deserializes into o the last items; amount specified by count, ordered by col.
		Latest(typ CredentialTypeIdentifier, col string, count uint64, o interface{}) error
		// Close the database.
		Close() error
	}

	// sqlRevStorage implements the revStorage interface, storing any record type in a SQL database,
	// for use by revocation servers.
	sqlRevStorage struct {
		gorm *gorm.DB
	}

45
	// memRevStorage is a much simpler in-memory database, suitable only for storing update messages.
46
47
	memRevStorage struct {
		sync.Mutex
48
		records map[CredentialTypeIdentifier]*memUpdateRecord
49
50
	}

51
	memUpdateRecord struct {
52
		sync.Mutex
53
		r *revocation.Update
54
55
56
57
58
	}
)

func newMemStorage() memRevStorage {
	return memRevStorage{
59
		records: make(map[CredentialTypeIdentifier]*memUpdateRecord),
60
61
62
	}
}

63
func (m memRevStorage) get(typ CredentialTypeIdentifier) *memUpdateRecord {
64
65
66
67
68
	m.Lock()
	defer m.Unlock()
	return m.records[typ]
}

69
70
71
72
73
74
75
func (m memRevStorage) Latest(typ CredentialTypeIdentifier, count uint64) *revocation.Update {
	record := m.get(typ)
	if record == nil {
		return nil
	}
	record.Lock()
	defer record.Unlock()
76

77
78
79
	offset := int64(len(record.r.Events)) - int64(count) - 1
	if offset < 0 {
		offset = 0
80
	}
81
82
83
84
	response := &revocation.Update{SignedAccumulator: record.r.SignedAccumulator}
	for _, rec := range record.r.Events[offset:] {
		Logger.Trace("membdb: get ", rec.Index)
		response.Events = append(response.Events, rec)
85
	}
86
	return response
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
func (m memRevStorage) Insert(typ CredentialTypeIdentifier, update *revocation.Update) {
	record := m.get(typ)
	if record == nil {
		record = &memUpdateRecord{r: &revocation.Update{}}
		m.records[typ] = record
	}
	record.Lock()
	defer record.Unlock()

	ours := record.r.Events
	if len(ours) == 0 {
		record.r = update
		return
	}
	theirs := update.Events
	if len(theirs) == 0 {
		return
	}
	theirStart, theirEnd, ourEnd := theirs[0].Index, theirs[len(theirs)-1].Index, ours[len(ours)-1].Index
	offset := ourEnd - theirStart
	if theirEnd <= ourEnd || offset < 0 {
		return
	}
112

113
114
115
	Logger.Trace("membdb: inserting")
	record.r.SignedAccumulator = update.SignedAccumulator
	record.r.Events = append(record.r.Events, theirs[offset:]...)
116
117
118
}

func (m memRevStorage) HasRecords(typ CredentialTypeIdentifier) bool {
119
120
121
122
123
124
125
	record := m.get(typ)
	if record == nil {
		return false
	}
	record.Lock()
	defer record.Unlock()
	return len(record.r.Events) > 0
126
127
128
129
130
131
132
133
134
135
136
137
}

func newSqlStorage(debug bool, db string) (revStorage, error) {
	g, err := gorm.Open("postgres", db)
	if err != nil {
		return nil, err
	}

	if debug {
		g.LogMode(true)
		g.SetLogger(gorm.Logger{LogWriter: log.New(Logger.WriterLevel(logrus.DebugLevel), "db: ", 0)})
	}
138
139
140
141
	if g.AutoMigrate((*EventRecord)(nil)); g.Error != nil {
		return nil, g.Error
	}
	if g.AutoMigrate((*AccumulatorRecord)(nil)); g.Error != nil {
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
		return nil, g.Error
	}
	if g.AutoMigrate((*IssuanceRecord)(nil)); g.Error != nil {
		return nil, g.Error
	}

	return sqlRevStorage{gorm: g}, nil
}

func (s sqlRevStorage) Close() error {
	return s.gorm.Close()
}

func (s sqlRevStorage) Transaction(f func(tx revStorage) error) (err error) {
	tx := sqlRevStorage{gorm: s.gorm.Begin()}
	defer func() {
		if e := recover(); err != nil {
			err = errors.WrapPrefix(e, "panic in db transaction", 0)
			tx.gorm.Rollback()
		}
	}()

	if err = f(tx); err != nil {
		tx.gorm.Rollback()
		return err
	}

	err = tx.gorm.Commit().Error
	return
}

func (s sqlRevStorage) Get(typ CredentialTypeIdentifier, col string, key interface{}, o interface{}) error {
	return s.gorm.First(o, fmt.Sprintf("cred_type = ? and %s = ?", col), typ, key).Error
}

func (s sqlRevStorage) Insert(o interface{}) error {
	return s.gorm.Create(o).Error
}

func (s sqlRevStorage) Save(o interface{}) error {
	return s.gorm.Save(o).Error
}

185
186
187
188
189
190
191
192
193
194
func (s sqlRevStorage) Upsert(o interface{}) error {
	var c int
	s.gorm.Model(o).Count(&c)
	if c == 0 {
		return s.Insert(o)
	} else {
		return s.Save(o)
	}
}

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
func (s sqlRevStorage) Last(typ CredentialTypeIdentifier, o interface{}) error {
	return s.gorm.Last(o, "cred_type = ?", typ).Error
}

func (s sqlRevStorage) Exists(typ CredentialTypeIdentifier, col string, key interface{}, o interface{}) (bool, error) {
	var c int
	s.gorm.Model(o).
		Where(fmt.Sprintf("cred_type = ? and %s = ?", col), typ, key).
		Count(&c)
	return c > 0, s.gorm.Error
}

func (s sqlRevStorage) HasRecords(typ CredentialTypeIdentifier, o interface{}) (bool, error) {
	var c int
	s.gorm.Model(o).
		Where("cred_type = ?", typ).
		Count(&c)
	return c > 0, s.gorm.Error
}

func (s sqlRevStorage) From(typ CredentialTypeIdentifier, col string, key interface{}, o interface{}) error {
	return s.gorm.Where(fmt.Sprintf("cred_type = ? and %s >= ?", col), typ, key).Order(col + " asc").Find(o).Error
}

func (s sqlRevStorage) Latest(typ CredentialTypeIdentifier, col string, count uint64, o interface{}) error {
	return s.gorm.Where("cred_type = ?", typ).Order(col + " asc").Limit(count).Find(o).Error
}