Skip to content

Commit b7d4bbb

Browse files
authored
fix: add loading session for each encryption - improve encrypt func (#6)
* fix: add loading session for each encryption - improve encrypt func fix issues caused by caching outdated session * test: add tests for situation when session does not exist
1 parent 17c6921 commit b7d4bbb

2 files changed

Lines changed: 194 additions & 257 deletions

File tree

Sources/DXProtocol/Session/Session.swift

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -231,20 +231,24 @@ public struct Session: Codable {
231231
/// - identityStore: The identity store.
232232
///
233233
/// - Returns: The encrypted message container.
234-
public mutating func encrypt(data: Data,
235-
for address: ProtocolAddress,
236-
sessionStore: SessionStorable,
237-
identityStore: IdentityKeyStorable) throws -> MessageContainer {
234+
public static func encrypt(data: Data,
235+
for address: ProtocolAddress,
236+
sessionStore: SessionStorable,
237+
identityStore: IdentityKeyStorable) throws -> MessageContainer {
238238
let lock = SessionLock(address: address)
239239
lock.lock()
240240
defer { lock.unlock() }
241241

242-
let result = try self.state.encrypt(
243-
data: data,
244-
sessionStore: sessionStore,
245-
identityStore: identityStore)
246-
try sessionStore.storeSession(self, for: address)
247-
242+
guard var session = try sessionStore.loadSession(for: address) else {
243+
throw DXError.sessionNotFound("Failed to find session while encrypting message")
244+
}
245+
246+
let result = try session.state.encrypt(
247+
data: data,
248+
sessionStore: sessionStore,
249+
identityStore: identityStore)
250+
try sessionStore.storeSession(session, for: address)
251+
248252
return result
249253
}
250254

@@ -367,7 +371,6 @@ extension Session {
367371
lock.lock()
368372
defer { lock.unlock() }
369373

370-
// This code is not covered by tests
371374
guard var session = try sessionStore.loadSession(for: address) else {
372375
throw DXError.sessionNotFound("Failed to find session while decrypting message")
373376
}

0 commit comments

Comments
 (0)