1 package org
.asamk
.signal
.manager
.storage
;
3 import com
.fasterxml
.jackson
.databind
.JsonNode
;
4 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
6 import org
.asamk
.signal
.manager
.Settings
;
7 import org
.asamk
.signal
.manager
.api
.Contact
;
8 import org
.asamk
.signal
.manager
.api
.GroupId
;
9 import org
.asamk
.signal
.manager
.api
.Pair
;
10 import org
.asamk
.signal
.manager
.api
.Profile
;
11 import org
.asamk
.signal
.manager
.api
.ServiceEnvironment
;
12 import org
.asamk
.signal
.manager
.api
.TrustLevel
;
13 import org
.asamk
.signal
.manager
.helper
.RecipientAddressResolver
;
14 import org
.asamk
.signal
.manager
.storage
.configuration
.ConfigurationStore
;
15 import org
.asamk
.signal
.manager
.storage
.configuration
.LegacyConfigurationStore
;
16 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactsStore
;
17 import org
.asamk
.signal
.manager
.storage
.contacts
.LegacyJsonContactsStore
;
18 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
19 import org
.asamk
.signal
.manager
.storage
.groups
.GroupStore
;
20 import org
.asamk
.signal
.manager
.storage
.groups
.LegacyGroupStore
;
21 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityKeyStore
;
22 import org
.asamk
.signal
.manager
.storage
.identities
.LegacyIdentityKeyStore
;
23 import org
.asamk
.signal
.manager
.storage
.identities
.SignalIdentityKeyStore
;
24 import org
.asamk
.signal
.manager
.storage
.keyValue
.KeyValueEntry
;
25 import org
.asamk
.signal
.manager
.storage
.keyValue
.KeyValueStore
;
26 import org
.asamk
.signal
.manager
.storage
.messageCache
.MessageCache
;
27 import org
.asamk
.signal
.manager
.storage
.prekeys
.KyberPreKeyStore
;
28 import org
.asamk
.signal
.manager
.storage
.prekeys
.LegacyPreKeyStore
;
29 import org
.asamk
.signal
.manager
.storage
.prekeys
.LegacySignedPreKeyStore
;
30 import org
.asamk
.signal
.manager
.storage
.prekeys
.PreKeyStore
;
31 import org
.asamk
.signal
.manager
.storage
.prekeys
.SignedPreKeyStore
;
32 import org
.asamk
.signal
.manager
.storage
.profiles
.LegacyProfileStore
;
33 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
34 import org
.asamk
.signal
.manager
.storage
.protocol
.LegacyJsonSignalProtocolStore
;
35 import org
.asamk
.signal
.manager
.storage
.protocol
.SignalProtocolStore
;
36 import org
.asamk
.signal
.manager
.storage
.recipients
.CdsiStore
;
37 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore
;
38 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore2
;
39 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
40 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
41 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientIdCreator
;
42 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientResolver
;
43 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientStore
;
44 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientTrustedResolver
;
45 import org
.asamk
.signal
.manager
.storage
.sendLog
.MessageSendLogStore
;
46 import org
.asamk
.signal
.manager
.storage
.senderKeys
.LegacySenderKeyRecordStore
;
47 import org
.asamk
.signal
.manager
.storage
.senderKeys
.LegacySenderKeySharedStore
;
48 import org
.asamk
.signal
.manager
.storage
.senderKeys
.SenderKeyStore
;
49 import org
.asamk
.signal
.manager
.storage
.sessions
.LegacySessionStore
;
50 import org
.asamk
.signal
.manager
.storage
.sessions
.SessionStore
;
51 import org
.asamk
.signal
.manager
.storage
.stickers
.LegacyStickerStore
;
52 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerStore
;
53 import org
.asamk
.signal
.manager
.storage
.threads
.LegacyJsonThreadStore
;
54 import org
.asamk
.signal
.manager
.util
.IOUtils
;
55 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
56 import org
.signal
.libsignal
.protocol
.IdentityKeyPair
;
57 import org
.signal
.libsignal
.protocol
.InvalidMessageException
;
58 import org
.signal
.libsignal
.protocol
.SignalProtocolAddress
;
59 import org
.signal
.libsignal
.protocol
.state
.KyberPreKeyRecord
;
60 import org
.signal
.libsignal
.protocol
.state
.PreKeyRecord
;
61 import org
.signal
.libsignal
.protocol
.state
.SessionRecord
;
62 import org
.signal
.libsignal
.protocol
.state
.SignedPreKeyRecord
;
63 import org
.signal
.libsignal
.protocol
.util
.KeyHelper
;
64 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
65 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
66 import org
.slf4j
.Logger
;
67 import org
.slf4j
.LoggerFactory
;
68 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountDataStore
;
69 import org
.whispersystems
.signalservice
.api
.SignalServiceDataStore
;
70 import org
.whispersystems
.signalservice
.api
.account
.AccountAttributes
;
71 import org
.whispersystems
.signalservice
.api
.account
.PreKeyCollection
;
72 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
73 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
74 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
75 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
76 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
77 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
78 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
79 import org
.whispersystems
.signalservice
.api
.storage
.SignalStorageManifest
;
80 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
81 import org
.whispersystems
.signalservice
.api
.util
.CredentialsProvider
;
82 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
84 import java
.io
.ByteArrayInputStream
;
85 import java
.io
.ByteArrayOutputStream
;
86 import java
.io
.Closeable
;
88 import java
.io
.FileInputStream
;
89 import java
.io
.FileOutputStream
;
90 import java
.io
.IOException
;
91 import java
.io
.RandomAccessFile
;
92 import java
.nio
.channels
.Channels
;
93 import java
.nio
.channels
.ClosedChannelException
;
94 import java
.nio
.channels
.FileChannel
;
95 import java
.nio
.channels
.FileLock
;
96 import java
.nio
.file
.Files
;
97 import java
.sql
.Connection
;
98 import java
.sql
.SQLException
;
99 import java
.util
.Base64
;
100 import java
.util
.Comparator
;
101 import java
.util
.HashSet
;
102 import java
.util
.List
;
103 import java
.util
.Optional
;
104 import java
.util
.function
.Function
;
105 import java
.util
.function
.Supplier
;
107 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.PREKEY_MAXIMUM_ID
;
108 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.getCapabilities
;
110 public class SignalAccount
implements Closeable
{
112 private final static Logger logger
= LoggerFactory
.getLogger(SignalAccount
.class);
114 private static final int MINIMUM_STORAGE_VERSION
= 1;
115 private static final int CURRENT_STORAGE_VERSION
= 8;
117 private final Object LOCK
= new Object();
119 private final ObjectMapper jsonProcessor
= Utils
.createStorageObjectMapper();
121 private final FileChannel fileChannel
;
122 private final FileLock lock
;
124 private int previousStorageVersion
;
126 private File dataPath
;
127 private String accountPath
;
129 private ServiceEnvironment serviceEnvironment
;
130 private String number
;
131 private String username
;
132 private String encryptedDeviceName
;
133 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
134 private String password
;
135 private String registrationLockPin
;
136 private MasterKey pinMasterKey
;
137 private StorageKey storageKey
;
138 private ProfileKey profileKey
;
140 private Settings settings
;
142 private final KeyValueEntry
<String
> verificationSessionId
= new KeyValueEntry
<>("verification-session-id",
144 private final KeyValueEntry
<String
> verificationSessionNumber
= new KeyValueEntry
<>("verification-session-number",
146 private final KeyValueEntry
<Long
> lastReceiveTimestamp
= new KeyValueEntry
<>("last-receive-timestamp",
149 private final KeyValueEntry
<byte[]> cdsiToken
= new KeyValueEntry
<>("cdsi-token", byte[].class);
150 private final KeyValueEntry
<Long
> lastRecipientsRefresh
= new KeyValueEntry
<>("last-recipients-refresh",
152 private final KeyValueEntry
<Long
> storageManifestVersion
= new KeyValueEntry
<>("storage-manifest-version",
155 private boolean isMultiDevice
= false;
156 private boolean registered
= false;
158 private final AccountData
<ACI
> aciAccountData
= new AccountData
<>(ServiceIdType
.ACI
);
159 private final AccountData
<PNI
> pniAccountData
= new AccountData
<>(ServiceIdType
.PNI
);
160 private IdentityKeyStore identityKeyStore
;
161 private SenderKeyStore senderKeyStore
;
162 private GroupStore groupStore
;
163 private RecipientStore recipientStore
;
164 private StickerStore stickerStore
;
165 private ConfigurationStore configurationStore
;
166 private KeyValueStore keyValueStore
;
167 private CdsiStore cdsiStore
;
169 private MessageCache messageCache
;
170 private MessageSendLogStore messageSendLogStore
;
172 private AccountDatabase accountDatabase
;
174 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
175 this.fileChannel
= fileChannel
;
179 public static SignalAccount
load(
180 File dataPath
, String accountPath
, boolean waitForLock
, final Settings settings
181 ) throws IOException
{
182 logger
.trace("Opening account file");
183 final var fileName
= getFileName(dataPath
, accountPath
);
184 final var pair
= openFileChannel(fileName
, waitForLock
);
186 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
187 logger
.trace("Loading account file");
188 signalAccount
.load(dataPath
, accountPath
, settings
);
189 logger
.trace("Migrating legacy parts of account file");
190 signalAccount
.migrateLegacyConfigs();
192 return signalAccount
;
193 } catch (Throwable e
) {
194 pair
.second().close();
195 pair
.first().close();
200 public static SignalAccount
create(
204 ServiceEnvironment serviceEnvironment
,
205 IdentityKeyPair aciIdentityKey
,
206 IdentityKeyPair pniIdentityKey
,
208 int pniRegistrationId
,
209 ProfileKey profileKey
,
210 final Settings settings
211 ) throws IOException
{
212 IOUtils
.createPrivateDirectories(dataPath
);
213 var fileName
= getFileName(dataPath
, accountPath
);
214 if (!fileName
.exists()) {
215 IOUtils
.createPrivateFile(fileName
);
218 final var pair
= openFileChannel(fileName
, true);
219 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
221 signalAccount
.accountPath
= accountPath
;
222 signalAccount
.number
= number
;
223 signalAccount
.serviceEnvironment
= serviceEnvironment
;
224 signalAccount
.profileKey
= profileKey
;
225 signalAccount
.password
= KeyUtils
.createPassword();
227 signalAccount
.dataPath
= dataPath
;
228 signalAccount
.aciAccountData
.setIdentityKeyPair(aciIdentityKey
);
229 signalAccount
.pniAccountData
.setIdentityKeyPair(pniIdentityKey
);
230 signalAccount
.aciAccountData
.setLocalRegistrationId(registrationId
);
231 signalAccount
.pniAccountData
.setLocalRegistrationId(pniRegistrationId
);
232 signalAccount
.settings
= settings
;
234 signalAccount
.registered
= false;
236 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
237 signalAccount
.migrateLegacyConfigs();
238 signalAccount
.clearAllPreKeys();
239 signalAccount
.save();
241 return signalAccount
;
244 private static SignalAccount
createLinkedAccount(
248 ServiceEnvironment serviceEnvironment
,
252 String encryptedDeviceName
,
254 IdentityKeyPair aciIdentityKey
,
255 IdentityKeyPair pniIdentityKey
,
257 int pniRegistrationId
,
258 ProfileKey profileKey
,
259 final Settings settings
260 ) throws IOException
{
261 var fileName
= getFileName(dataPath
, accountPath
);
262 IOUtils
.createPrivateFile(fileName
);
264 final var pair
= openFileChannel(fileName
, true);
265 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
267 signalAccount
.dataPath
= dataPath
;
268 signalAccount
.accountPath
= accountPath
;
269 signalAccount
.serviceEnvironment
= serviceEnvironment
;
270 signalAccount
.aciAccountData
.setLocalRegistrationId(registrationId
);
271 signalAccount
.pniAccountData
.setLocalRegistrationId(pniRegistrationId
);
272 signalAccount
.settings
= settings
;
273 signalAccount
.setProvisioningData(number
,
283 signalAccount
.getRecipientTrustedResolver()
284 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
285 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
286 signalAccount
.migrateLegacyConfigs();
287 signalAccount
.clearAllPreKeys();
288 signalAccount
.save();
290 return signalAccount
;
293 public static SignalAccount
createOrUpdateLinkedAccount(
297 ServiceEnvironment serviceEnvironment
,
301 String encryptedDeviceName
,
303 IdentityKeyPair aciIdentityKey
,
304 IdentityKeyPair pniIdentityKey
,
306 int pniRegistrationId
,
307 ProfileKey profileKey
,
308 final Settings settings
309 ) throws IOException
{
310 IOUtils
.createPrivateDirectories(dataPath
);
311 var fileName
= getFileName(dataPath
, accountPath
);
312 if (!fileName
.exists()) {
313 return createLinkedAccount(dataPath
,
330 final var signalAccount
= load(dataPath
, accountPath
, true, settings
);
331 signalAccount
.setProvisioningData(number
,
340 signalAccount
.getRecipientTrustedResolver()
341 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
342 signalAccount
.aciAccountData
.getSessionStore().archiveAllSessions();
343 signalAccount
.pniAccountData
.getSessionStore().archiveAllSessions();
344 signalAccount
.getSenderKeyStore().deleteAll();
345 signalAccount
.clearAllPreKeys();
346 return signalAccount
;
349 private void setProvisioningData(
353 final String password
,
354 final String encryptedDeviceName
,
356 final IdentityKeyPair aciIdentity
,
357 final IdentityKeyPair pniIdentity
,
358 final ProfileKey profileKey
360 this.number
= number
;
361 this.aciAccountData
.setServiceId(aci
);
362 this.pniAccountData
.setServiceId(pni
);
363 this.password
= password
;
364 this.profileKey
= profileKey
;
365 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
366 this.encryptedDeviceName
= encryptedDeviceName
;
367 this.deviceId
= deviceId
;
368 this.aciAccountData
.setIdentityKeyPair(aciIdentity
);
369 this.pniAccountData
.setIdentityKeyPair(pniIdentity
);
370 this.registered
= true;
371 this.isMultiDevice
= true;
372 getKeyValueStore().storeEntry(lastReceiveTimestamp
, 0L);
373 this.pinMasterKey
= null;
374 getKeyValueStore().storeEntry(storageManifestVersion
, -1L);
375 this.setStorageManifest(null);
376 this.storageKey
= null;
377 trustSelfIdentity(ServiceIdType
.ACI
);
378 trustSelfIdentity(ServiceIdType
.PNI
);
379 getKeyValueStore().storeEntry(lastRecipientsRefresh
, null);
382 public void finishRegistration(
385 final MasterKey masterKey
,
387 final PreKeyCollection aciPreKeys
,
388 final PreKeyCollection pniPreKeys
390 this.pinMasterKey
= masterKey
;
391 getKeyValueStore().storeEntry(storageManifestVersion
, -1L);
392 this.setStorageManifest(null);
393 this.storageKey
= null;
394 this.encryptedDeviceName
= null;
395 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
396 this.isMultiDevice
= false;
397 this.registered
= true;
398 this.aciAccountData
.setServiceId(aci
);
399 this.pniAccountData
.setServiceId(pni
);
400 this.registrationLockPin
= pin
;
401 getKeyValueStore().storeEntry(lastReceiveTimestamp
, 0L);
404 setPreKeys(ServiceIdType
.ACI
, aciPreKeys
);
405 setPreKeys(ServiceIdType
.PNI
, pniPreKeys
);
406 aciAccountData
.getSessionStore().archiveAllSessions();
407 pniAccountData
.getSessionStore().archiveAllSessions();
408 getSenderKeyStore().deleteAll();
409 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
410 trustSelfIdentity(ServiceIdType
.ACI
);
411 trustSelfIdentity(ServiceIdType
.PNI
);
412 getKeyValueStore().storeEntry(lastRecipientsRefresh
, null);
415 public void initDatabase() {
416 getAccountDatabase();
419 private void migrateLegacyConfigs() {
420 if (isPrimaryDevice() && getPniIdentityKeyPair() == null) {
421 setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
425 private void mergeRecipients(
426 final Connection connection
, RecipientId recipientId
, RecipientId toBeMergedRecipientId
427 ) throws SQLException
{
428 getMessageCache().mergeRecipients(recipientId
, toBeMergedRecipientId
);
429 getGroupStore().mergeRecipients(connection
, recipientId
, toBeMergedRecipientId
);
432 public void removeRecipient(final RecipientId recipientId
) {
433 final var recipientAddress
= getRecipientStore().resolveRecipientAddress(recipientId
);
434 if (recipientAddress
.matches(getSelfRecipientAddress())) {
435 throw new RuntimeException("Can't delete self recipient");
437 getRecipientStore().deleteRecipientData(recipientId
);
438 getMessageCache().deleteMessages(recipientId
);
439 if (recipientAddress
.serviceId().isPresent()) {
440 final var serviceId
= recipientAddress
.serviceId().get();
441 aciAccountData
.getSessionStore().deleteAllSessions(serviceId
);
442 pniAccountData
.getSessionStore().deleteAllSessions(serviceId
);
443 getIdentityKeyStore().deleteIdentity(serviceId
);
444 getSenderKeyStore().deleteAll(serviceId
);
448 public static File
getFileName(File dataPath
, String account
) {
449 return new File(dataPath
, account
);
452 private static File
getUserPath(final File dataPath
, final String account
) {
453 final var path
= new File(dataPath
, account
+ ".d");
455 IOUtils
.createPrivateDirectories(path
);
456 } catch (IOException e
) {
457 throw new AssertionError("Failed to create user path", e
);
462 private static File
getMessageCachePath(File dataPath
, String account
) {
463 return new File(getUserPath(dataPath
, account
), "msg-cache");
466 private static File
getStorageManifestFile(File dataPath
, String account
) {
467 return new File(getUserPath(dataPath
, account
), "storage-manifest");
470 private static File
getDatabaseFile(File dataPath
, String account
) {
471 return new File(getUserPath(dataPath
, account
), "account.db");
474 public static boolean accountFileExists(File dataPath
, String account
) {
475 if (account
== null) {
478 var f
= getFileName(dataPath
, account
);
479 return !(!f
.exists() || f
.isDirectory());
483 File dataPath
, String accountPath
, final Settings settings
484 ) throws IOException
{
485 this.dataPath
= dataPath
;
486 this.accountPath
= accountPath
;
487 this.settings
= settings
;
488 final JsonNode rootNode
;
489 synchronized (fileChannel
) {
490 fileChannel
.position(0);
491 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
494 var migratedLegacyConfig
= false;
496 if (rootNode
.hasNonNull("version")) {
497 var accountVersion
= rootNode
.get("version").asInt(1);
498 if (accountVersion
> CURRENT_STORAGE_VERSION
) {
499 throw new IOException("Config file was created by a more recent version: " + accountVersion
);
500 } else if (accountVersion
< MINIMUM_STORAGE_VERSION
) {
501 throw new IOException("Config file was created by a no longer supported older version: "
504 previousStorageVersion
= accountVersion
;
505 if (accountVersion
< CURRENT_STORAGE_VERSION
) {
506 migratedLegacyConfig
= true;
510 if (previousStorageVersion
< 8) {
511 final var userPath
= getUserPath(dataPath
, accountPath
);
512 loadLegacyFile(userPath
, rootNode
);
513 migratedLegacyConfig
= true;
515 final var storage
= jsonProcessor
.convertValue(rootNode
, Storage
.class);
516 serviceEnvironment
= ServiceEnvironment
.valueOf(storage
.serviceEnvironment
);
517 registered
= storage
.registered
;
518 number
= storage
.number
;
519 username
= storage
.username
;
520 encryptedDeviceName
= storage
.encryptedDeviceName
;
521 deviceId
= storage
.deviceId
;
522 isMultiDevice
= storage
.isMultiDevice
;
523 password
= storage
.password
;
524 setAccountData(aciAccountData
, storage
.aciAccountData
, ACI
::parseOrThrow
);
525 setAccountData(pniAccountData
, storage
.pniAccountData
, PNI
::parseOrThrow
);
526 registrationLockPin
= storage
.registrationLockPin
;
527 final var base64
= Base64
.getDecoder();
528 if (storage
.pinMasterKey
!= null) {
529 pinMasterKey
= new MasterKey(base64
.decode(storage
.pinMasterKey
));
531 if (storage
.storageKey
!= null) {
532 storageKey
= new StorageKey(base64
.decode(storage
.storageKey
));
534 if (storage
.profileKey
!= null) {
536 profileKey
= new ProfileKey(base64
.decode(storage
.profileKey
));
537 } catch (InvalidInputException e
) {
538 throw new IOException(
539 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
546 if (migratedLegacyConfig
) {
551 private <SERVICE_ID
extends ServiceId
> void setAccountData(
552 AccountData
<SERVICE_ID
> accountData
,
553 Storage
.AccountData storage
,
554 Function
<String
, SERVICE_ID
> serviceIdParser
555 ) throws IOException
{
556 if (storage
.serviceId
!= null) {
558 accountData
.setServiceId(serviceIdParser
.apply(storage
.serviceId
));
559 } catch (IllegalArgumentException e
) {
560 throw new IOException("Config file contains an invalid serviceId, needs to be a valid UUID", e
);
563 accountData
.setLocalRegistrationId(storage
.registrationId
);
564 if (storage
.identityPrivateKey
!= null && storage
.identityPublicKey
!= null) {
565 final var base64
= Base64
.getDecoder();
566 final var publicKeyBytes
= base64
.decode(storage
.identityPublicKey
);
567 final var privateKeyBytes
= base64
.decode(storage
.identityPrivateKey
);
568 final var keyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
569 accountData
.setIdentityKeyPair(keyPair
);
571 accountData
.preKeyMetadata
.nextPreKeyId
= storage
.nextPreKeyId
;
572 accountData
.preKeyMetadata
.nextSignedPreKeyId
= storage
.nextSignedPreKeyId
;
573 accountData
.preKeyMetadata
.activeSignedPreKeyId
= storage
.activeSignedPreKeyId
;
574 accountData
.preKeyMetadata
.nextKyberPreKeyId
= storage
.nextKyberPreKeyId
;
575 accountData
.preKeyMetadata
.activeLastResortKyberPreKeyId
= storage
.activeLastResortKyberPreKeyId
;
578 private void loadLegacyFile(final File userPath
, final JsonNode rootNode
) throws IOException
{
579 number
= Utils
.getNotNullNode(rootNode
, "username").asText();
580 if (rootNode
.hasNonNull("password")) {
581 password
= rootNode
.get("password").asText();
583 if (password
== null) {
584 password
= KeyUtils
.createPassword();
587 if (rootNode
.hasNonNull("serviceEnvironment")) {
588 serviceEnvironment
= ServiceEnvironment
.valueOf(rootNode
.get("serviceEnvironment").asText());
590 if (serviceEnvironment
== null) {
591 serviceEnvironment
= ServiceEnvironment
.LIVE
;
593 registered
= Utils
.getNotNullNode(rootNode
, "registered").asBoolean();
594 if (rootNode
.hasNonNull("usernameIdentifier")) {
595 username
= rootNode
.get("usernameIdentifier").asText();
597 if (rootNode
.hasNonNull("uuid")) {
599 aciAccountData
.setServiceId(ACI
.parseOrThrow(rootNode
.get("uuid").asText()));
600 } catch (IllegalArgumentException e
) {
601 throw new IOException("Config file contains an invalid aci/uuid, needs to be a valid UUID", e
);
604 if (rootNode
.hasNonNull("pni")) {
606 pniAccountData
.setServiceId(PNI
.parseOrThrow(rootNode
.get("pni").asText()));
607 } catch (IllegalArgumentException e
) {
608 throw new IOException("Config file contains an invalid pni, needs to be a valid UUID", e
);
611 if (rootNode
.hasNonNull("sessionId")) {
612 getKeyValueStore().storeEntry(verificationSessionId
, rootNode
.get("sessionId").asText());
614 if (rootNode
.hasNonNull("sessionNumber")) {
615 getKeyValueStore().storeEntry(verificationSessionNumber
, rootNode
.get("sessionNumber").asText());
617 if (rootNode
.hasNonNull("deviceName")) {
618 encryptedDeviceName
= rootNode
.get("deviceName").asText();
620 if (rootNode
.hasNonNull("deviceId")) {
621 deviceId
= rootNode
.get("deviceId").asInt();
623 if (rootNode
.hasNonNull("isMultiDevice")) {
624 isMultiDevice
= rootNode
.get("isMultiDevice").asBoolean();
626 if (rootNode
.hasNonNull("lastReceiveTimestamp")) {
627 getKeyValueStore().storeEntry(lastReceiveTimestamp
, rootNode
.get("lastReceiveTimestamp").asLong());
629 int registrationId
= 0;
630 if (rootNode
.hasNonNull("registrationId")) {
631 registrationId
= rootNode
.get("registrationId").asInt();
633 if (rootNode
.hasNonNull("pniRegistrationId")) {
634 pniAccountData
.setLocalRegistrationId(rootNode
.get("pniRegistrationId").asInt());
636 pniAccountData
.setLocalRegistrationId(KeyHelper
.generateRegistrationId(false));
638 IdentityKeyPair aciIdentityKeyPair
= null;
639 if (rootNode
.hasNonNull("identityPrivateKey") && rootNode
.hasNonNull("identityKey")) {
640 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityKey").asText());
641 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityPrivateKey").asText());
642 aciIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
644 if (rootNode
.hasNonNull("pniIdentityPrivateKey") && rootNode
.hasNonNull("pniIdentityKey")) {
645 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityKey").asText());
646 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityPrivateKey").asText());
647 pniAccountData
.setIdentityKeyPair(KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
));
650 if (rootNode
.hasNonNull("registrationLockPin")) {
651 registrationLockPin
= rootNode
.get("registrationLockPin").asText();
653 if (rootNode
.hasNonNull("pinMasterKey")) {
654 pinMasterKey
= new MasterKey(Base64
.getDecoder().decode(rootNode
.get("pinMasterKey").asText()));
656 if (rootNode
.hasNonNull("storageKey")) {
657 storageKey
= new StorageKey(Base64
.getDecoder().decode(rootNode
.get("storageKey").asText()));
659 if (rootNode
.hasNonNull("storageManifestVersion")) {
660 getKeyValueStore().storeEntry(storageManifestVersion
, rootNode
.get("storageManifestVersion").asLong());
662 if (rootNode
.hasNonNull("preKeyIdOffset")) {
663 aciAccountData
.preKeyMetadata
.nextPreKeyId
= rootNode
.get("preKeyIdOffset").asInt(1);
665 aciAccountData
.preKeyMetadata
.nextPreKeyId
= getRandomPreKeyIdOffset();
667 if (rootNode
.hasNonNull("nextSignedPreKeyId")) {
668 aciAccountData
.preKeyMetadata
.nextSignedPreKeyId
= rootNode
.get("nextSignedPreKeyId").asInt(1);
670 aciAccountData
.preKeyMetadata
.nextSignedPreKeyId
= getRandomPreKeyIdOffset();
672 if (rootNode
.hasNonNull("activeSignedPreKeyId")) {
673 aciAccountData
.preKeyMetadata
.activeSignedPreKeyId
= rootNode
.get("activeSignedPreKeyId").asInt(-1);
675 aciAccountData
.preKeyMetadata
.activeSignedPreKeyId
= -1;
677 if (rootNode
.hasNonNull("pniPreKeyIdOffset")) {
678 pniAccountData
.preKeyMetadata
.nextPreKeyId
= rootNode
.get("pniPreKeyIdOffset").asInt(1);
680 pniAccountData
.preKeyMetadata
.nextPreKeyId
= getRandomPreKeyIdOffset();
682 if (rootNode
.hasNonNull("pniNextSignedPreKeyId")) {
683 pniAccountData
.preKeyMetadata
.nextSignedPreKeyId
= rootNode
.get("pniNextSignedPreKeyId").asInt(1);
685 pniAccountData
.preKeyMetadata
.nextSignedPreKeyId
= getRandomPreKeyIdOffset();
687 if (rootNode
.hasNonNull("pniActiveSignedPreKeyId")) {
688 pniAccountData
.preKeyMetadata
.activeSignedPreKeyId
= rootNode
.get("pniActiveSignedPreKeyId").asInt(-1);
690 pniAccountData
.preKeyMetadata
.activeSignedPreKeyId
= -1;
692 if (rootNode
.hasNonNull("kyberPreKeyIdOffset")) {
693 aciAccountData
.preKeyMetadata
.nextKyberPreKeyId
= rootNode
.get("kyberPreKeyIdOffset").asInt(1);
695 aciAccountData
.preKeyMetadata
.nextKyberPreKeyId
= getRandomPreKeyIdOffset();
697 if (rootNode
.hasNonNull("activeLastResortKyberPreKeyId")) {
698 aciAccountData
.preKeyMetadata
.activeLastResortKyberPreKeyId
= rootNode
.get("activeLastResortKyberPreKeyId")
701 aciAccountData
.preKeyMetadata
.activeLastResortKyberPreKeyId
= -1;
703 if (rootNode
.hasNonNull("pniKyberPreKeyIdOffset")) {
704 pniAccountData
.preKeyMetadata
.nextKyberPreKeyId
= rootNode
.get("pniKyberPreKeyIdOffset").asInt(1);
706 pniAccountData
.preKeyMetadata
.nextKyberPreKeyId
= getRandomPreKeyIdOffset();
708 if (rootNode
.hasNonNull("pniActiveLastResortKyberPreKeyId")) {
709 pniAccountData
.preKeyMetadata
.activeLastResortKyberPreKeyId
= rootNode
.get(
710 "pniActiveLastResortKyberPreKeyId").asInt(-1);
712 pniAccountData
.preKeyMetadata
.activeLastResortKyberPreKeyId
= -1;
714 if (rootNode
.hasNonNull("profileKey")) {
716 profileKey
= new ProfileKey(Base64
.getDecoder().decode(rootNode
.get("profileKey").asText()));
717 } catch (InvalidInputException e
) {
718 throw new IOException(
719 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
723 if (profileKey
== null) {
724 // Old config file, creating new profile key
725 setProfileKey(KeyUtils
.createProfileKey());
727 getProfileStore().storeProfileKey(getSelfRecipientId(), getProfileKey());
729 if (previousStorageVersion
< 5) {
730 final var legacyRecipientsStoreFile
= new File(userPath
, "recipients-store");
731 if (legacyRecipientsStoreFile
.exists()) {
732 LegacyRecipientStore2
.migrate(legacyRecipientsStoreFile
, getRecipientStore());
733 // Ensure our profile key is stored in profile store
734 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
737 if (previousStorageVersion
< 6) {
738 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
740 final var legacyAciPreKeysPath
= new File(userPath
, "pre-keys");
741 if (legacyAciPreKeysPath
.exists()) {
742 LegacyPreKeyStore
.migrate(legacyAciPreKeysPath
, aciAccountData
.getPreKeyStore());
744 final var legacyPniPreKeysPath
= new File(userPath
, "pre-keys-pni");
745 if (legacyPniPreKeysPath
.exists()) {
746 LegacyPreKeyStore
.migrate(legacyPniPreKeysPath
, pniAccountData
.getPreKeyStore());
748 final var legacyAciSignedPreKeysPath
= new File(userPath
, "signed-pre-keys");
749 if (legacyAciSignedPreKeysPath
.exists()) {
750 LegacySignedPreKeyStore
.migrate(legacyAciSignedPreKeysPath
, aciAccountData
.getSignedPreKeyStore());
752 final var legacyPniSignedPreKeysPath
= new File(userPath
, "signed-pre-keys-pni");
753 if (legacyPniSignedPreKeysPath
.exists()) {
754 LegacySignedPreKeyStore
.migrate(legacyPniSignedPreKeysPath
, pniAccountData
.getSignedPreKeyStore());
756 final var legacySessionsPath
= new File(userPath
, "sessions");
757 if (legacySessionsPath
.exists()) {
758 LegacySessionStore
.migrate(legacySessionsPath
,
759 getRecipientResolver(),
760 getRecipientAddressResolver(),
761 aciAccountData
.getSessionStore());
763 final var legacyIdentitiesPath
= new File(userPath
, "identities");
764 if (legacyIdentitiesPath
.exists()) {
765 LegacyIdentityKeyStore
.migrate(legacyIdentitiesPath
,
766 getRecipientResolver(),
767 getRecipientAddressResolver(),
768 getIdentityKeyStore());
770 final var legacySignalProtocolStore
= rootNode
.hasNonNull("axolotlStore")
771 ? jsonProcessor
.convertValue(Utils
.getNotNullNode(rootNode
, "axolotlStore"),
772 LegacyJsonSignalProtocolStore
.class)
774 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
775 aciIdentityKeyPair
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentityKeyPair();
776 registrationId
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getLocalRegistrationId();
779 this.aciAccountData
.setIdentityKeyPair(aciIdentityKeyPair
);
780 this.aciAccountData
.setLocalRegistrationId(registrationId
);
782 loadLegacyStores(rootNode
, legacySignalProtocolStore
);
784 final var legacySenderKeysPath
= new File(userPath
, "sender-keys");
785 if (legacySenderKeysPath
.exists()) {
786 LegacySenderKeyRecordStore
.migrate(legacySenderKeysPath
,
787 getRecipientResolver(),
788 getRecipientAddressResolver(),
789 getSenderKeyStore());
791 final var legacySenderKeysSharedPath
= new File(userPath
, "shared-sender-keys-store");
792 if (legacySenderKeysSharedPath
.exists()) {
793 LegacySenderKeySharedStore
.migrate(legacySenderKeysSharedPath
,
794 getRecipientResolver(),
795 getRecipientAddressResolver(),
796 getSenderKeyStore());
798 if (rootNode
.hasNonNull("groupStore")) {
799 final var groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"),
800 LegacyGroupStore
.Storage
.class);
801 LegacyGroupStore
.migrate(groupStoreStorage
,
802 new File(userPath
, "group-cache"),
803 getRecipientResolver(),
807 if (rootNode
.hasNonNull("stickerStore")) {
808 final var storage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"),
809 LegacyStickerStore
.Storage
.class);
810 LegacyStickerStore
.migrate(storage
, getStickerStore());
813 if (rootNode
.hasNonNull("configurationStore")) {
814 final var configurationStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("configurationStore"),
815 LegacyConfigurationStore
.Storage
.class);
816 LegacyConfigurationStore
.migrate(configurationStoreStorage
, getConfigurationStore());
819 loadLegacyThreadStore(rootNode
);
822 private void loadLegacyStores(
823 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
825 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
826 if (legacyRecipientStoreNode
!= null) {
827 logger
.debug("Migrating legacy recipient store.");
828 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
829 if (legacyRecipientStore
!= null) {
830 legacyRecipientStore
.getAddresses()
831 .forEach(recipient
-> getRecipientStore().resolveRecipientTrusted(recipient
));
833 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
836 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
837 logger
.debug("Migrating legacy pre key store.");
838 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
840 aciAccountData
.getPreKeyStore().storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
841 } catch (InvalidMessageException e
) {
842 logger
.warn("Failed to migrate pre key, ignoring", e
);
847 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
848 logger
.debug("Migrating legacy signed pre key store.");
849 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
851 aciAccountData
.getSignedPreKeyStore()
852 .storeSignedPreKey(entry
.getKey(), new SignedPreKeyRecord(entry
.getValue()));
853 } catch (InvalidMessageException e
) {
854 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
859 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
860 logger
.debug("Migrating legacy session store.");
861 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
863 aciAccountData
.getSessionStore()
864 .storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(), session
.deviceId
),
865 new SessionRecord(session
.sessionRecord
));
866 } catch (Exception e
) {
867 logger
.warn("Failed to migrate session, ignoring", e
);
872 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
873 logger
.debug("Migrating legacy identity session store.");
874 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
875 if (identity
.getAddress().serviceId().isEmpty()) {
878 final var serviceId
= identity
.getAddress().serviceId().get();
879 getIdentityKeyStore().saveIdentity(serviceId
, identity
.getIdentityKey());
880 getIdentityKeyStore().setIdentityTrustLevel(serviceId
,
881 identity
.getIdentityKey(),
882 identity
.getTrustLevel());
886 if (rootNode
.hasNonNull("contactStore")) {
887 logger
.debug("Migrating legacy contact store.");
888 final var contactStoreNode
= rootNode
.get("contactStore");
889 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
890 for (var contact
: contactStore
.getContacts()) {
891 final var recipientId
= getRecipientStore().resolveRecipientTrusted(contact
.getAddress());
892 getContactStore().storeContact(recipientId
,
893 new Contact(contact
.name
,
896 contact
.messageExpirationTime
,
901 // Store profile keys only in profile store
902 var profileKeyString
= contact
.profileKey
;
903 if (profileKeyString
!= null) {
904 final ProfileKey profileKey
;
906 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
907 getProfileStore().storeProfileKey(recipientId
, profileKey
);
908 } catch (InvalidInputException e
) {
909 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
915 if (rootNode
.hasNonNull("profileStore")) {
916 logger
.debug("Migrating legacy profile store.");
917 var profileStoreNode
= rootNode
.get("profileStore");
918 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
919 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
920 var recipientId
= getRecipientResolver().resolveRecipient(profileEntry
.address());
921 // Not migrating profile key credential here, it was changed to expiring profile key credentials
922 getProfileStore().storeProfileKey(recipientId
, profileEntry
.profileKey());
923 final var profile
= profileEntry
.profile();
924 if (profile
!= null) {
925 final var capabilities
= new HashSet
<Profile
.Capability
>();
926 if (profile
.getCapabilities() != null) {
927 if (profile
.getCapabilities().gv1Migration
) {
928 capabilities
.add(Profile
.Capability
.gv1Migration
);
930 if (profile
.getCapabilities().storage
) {
931 capabilities
.add(Profile
.Capability
.storage
);
934 final var newProfile
= new Profile(profileEntry
.lastUpdateTimestamp(),
935 profile
.getGivenName(),
936 profile
.getFamilyName(),
938 profile
.getAboutEmoji(),
941 profile
.isUnrestrictedUnidentifiedAccess()
942 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
943 : profile
.getUnidentifiedAccess() != null
944 ? Profile
.UnidentifiedAccessMode
.ENABLED
945 : Profile
.UnidentifiedAccessMode
.DISABLED
,
947 getProfileStore().storeProfile(recipientId
, newProfile
);
953 private void loadLegacyThreadStore(final JsonNode rootNode
) {
954 var threadStoreNode
= rootNode
.get("threadStore");
955 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
956 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
957 // Migrate thread info to group and contact store
958 for (var thread
: threadStore
.getThreads()) {
959 if (thread
.id
== null || thread
.id
.isEmpty()) {
963 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
964 final var recipientId
= getRecipientResolver().resolveRecipient(thread
.id
);
965 var contact
= getContactStore().getContact(recipientId
);
966 if (contact
!= null) {
967 getContactStore().storeContact(recipientId
,
968 Contact
.newBuilder(contact
)
969 .withMessageExpirationTime(thread
.messageExpirationTime
)
973 var groupInfo
= getGroupStore().getGroup(GroupId
.fromBase64(thread
.id
));
974 if (groupInfo
instanceof GroupInfoV1
) {
975 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
976 getGroupStore().updateGroup(groupInfo
);
979 } catch (Exception e
) {
980 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
986 private void save() {
987 synchronized (fileChannel
) {
988 final var base64
= Base64
.getEncoder();
989 final var storage
= new Storage(CURRENT_STORAGE_VERSION
,
990 serviceEnvironment
.name(),
998 Storage
.AccountData
.from(aciAccountData
),
999 Storage
.AccountData
.from(pniAccountData
),
1000 registrationLockPin
,
1001 pinMasterKey
== null ?
null : base64
.encodeToString(pinMasterKey
.serialize()),
1002 storageKey
== null ?
null : base64
.encodeToString(storageKey
.serialize()),
1003 profileKey
== null ?
null : base64
.encodeToString(profileKey
.serialize()));
1005 try (var output
= new ByteArrayOutputStream()) {
1006 // Write to memory first to prevent corrupting the file in case of serialization errors
1007 jsonProcessor
.writeValue(output
, storage
);
1008 var input
= new ByteArrayInputStream(output
.toByteArray());
1009 fileChannel
.position(0);
1010 input
.transferTo(Channels
.newOutputStream(fileChannel
));
1011 fileChannel
.truncate(fileChannel
.position());
1012 fileChannel
.force(false);
1014 } catch (Exception e
) {
1015 logger
.error("Error saving file: {}", e
.getMessage(), e
);
1020 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
1021 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
1023 var lock
= fileChannel
.tryLock();
1026 logger
.debug("Config file is in use by another instance.");
1027 throw new IOException("Config file is in use by another instance.");
1029 logger
.info("Config file is in use by another instance, waiting…");
1030 lock
= fileChannel
.lock();
1031 logger
.info("Config file lock acquired.");
1033 final var result
= new Pair
<>(fileChannel
, lock
);
1037 if (fileChannel
!= null) {
1038 fileChannel
.close();
1043 private void clearAllPreKeys() {
1044 clearAllPreKeys(ServiceIdType
.ACI
);
1045 clearAllPreKeys(ServiceIdType
.PNI
);
1048 private void clearAllPreKeys(ServiceIdType serviceIdType
) {
1049 final var accountData
= getAccountData(serviceIdType
);
1050 resetPreKeyOffsets(serviceIdType
);
1051 resetKyberPreKeyOffsets(serviceIdType
);
1052 accountData
.getPreKeyStore().removeAllPreKeys();
1053 accountData
.getSignedPreKeyStore().removeAllSignedPreKeys();
1054 accountData
.getKyberPreKeyStore().removeAllKyberPreKeys();
1058 private void setPreKeys(ServiceIdType serviceIdType
, PreKeyCollection preKeyCollection
) {
1059 final var accountData
= getAccountData(serviceIdType
);
1060 final var preKeyMetadata
= accountData
.getPreKeyMetadata();
1061 preKeyMetadata
.nextSignedPreKeyId
= preKeyCollection
.getSignedPreKey().getId();
1062 preKeyMetadata
.nextKyberPreKeyId
= preKeyCollection
.getLastResortKyberPreKey().getId();
1064 accountData
.getPreKeyStore().removeAllPreKeys();
1065 accountData
.getSignedPreKeyStore().removeAllSignedPreKeys();
1066 accountData
.getKyberPreKeyStore().removeAllKyberPreKeys();
1068 addSignedPreKey(serviceIdType
, preKeyCollection
.getSignedPreKey());
1069 addLastResortKyberPreKey(serviceIdType
, preKeyCollection
.getLastResortKyberPreKey());
1074 public void resetPreKeyOffsets(final ServiceIdType serviceIdType
) {
1075 final var preKeyMetadata
= getAccountData(serviceIdType
).getPreKeyMetadata();
1076 preKeyMetadata
.nextPreKeyId
= getRandomPreKeyIdOffset();
1077 preKeyMetadata
.nextSignedPreKeyId
= getRandomPreKeyIdOffset();
1078 preKeyMetadata
.activeSignedPreKeyId
= -1;
1082 private static int getRandomPreKeyIdOffset() {
1083 return KeyUtils
.getRandomInt(PREKEY_MAXIMUM_ID
);
1086 public void addPreKeys(ServiceIdType serviceIdType
, List
<PreKeyRecord
> records
) {
1087 final var accountData
= getAccountData(serviceIdType
);
1088 final var preKeyMetadata
= accountData
.getPreKeyMetadata();
1089 logger
.debug("Adding {} {} pre keys with offset {}",
1092 preKeyMetadata
.nextPreKeyId
);
1093 accountData
.getSignalServiceAccountDataStore()
1094 .markAllOneTimeEcPreKeysStaleIfNecessary(System
.currentTimeMillis());
1095 for (var record : records
) {
1096 if (preKeyMetadata
.nextPreKeyId
!= record.getId()) {
1097 logger
.error("Invalid pre key id {}, expected {}", record.getId(), preKeyMetadata
.nextPreKeyId
);
1098 throw new AssertionError("Invalid pre key id");
1100 accountData
.getPreKeyStore().storePreKey(record.getId(), record);
1101 preKeyMetadata
.nextPreKeyId
= (preKeyMetadata
.nextPreKeyId
+ 1) % PREKEY_MAXIMUM_ID
;
1106 public void addSignedPreKey(ServiceIdType serviceIdType
, SignedPreKeyRecord
record) {
1107 final var accountData
= getAccountData(serviceIdType
);
1108 final var preKeyMetadata
= accountData
.getPreKeyMetadata();
1109 logger
.debug("Adding {} signed pre key with offset {}", serviceIdType
, preKeyMetadata
.nextSignedPreKeyId
);
1110 if (preKeyMetadata
.nextSignedPreKeyId
!= record.getId()) {
1111 logger
.error("Invalid signed pre key id {}, expected {}",
1113 preKeyMetadata
.nextSignedPreKeyId
);
1114 throw new AssertionError("Invalid signed pre key id");
1116 accountData
.getSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
1117 preKeyMetadata
.nextSignedPreKeyId
= (preKeyMetadata
.nextSignedPreKeyId
+ 1) % PREKEY_MAXIMUM_ID
;
1118 preKeyMetadata
.activeSignedPreKeyId
= record.getId();
1122 public void resetKyberPreKeyOffsets(final ServiceIdType serviceIdType
) {
1123 final var preKeyMetadata
= getAccountData(serviceIdType
).getPreKeyMetadata();
1124 preKeyMetadata
.nextKyberPreKeyId
= getRandomPreKeyIdOffset();
1125 preKeyMetadata
.activeLastResortKyberPreKeyId
= -1;
1129 public void addKyberPreKeys(ServiceIdType serviceIdType
, List
<KyberPreKeyRecord
> records
) {
1130 final var accountData
= getAccountData(serviceIdType
);
1131 final var preKeyMetadata
= accountData
.getPreKeyMetadata();
1132 logger
.debug("Adding {} {} kyber pre keys with offset {}",
1135 preKeyMetadata
.nextKyberPreKeyId
);
1136 accountData
.getSignalServiceAccountDataStore()
1137 .markAllOneTimeEcPreKeysStaleIfNecessary(System
.currentTimeMillis());
1138 for (var record : records
) {
1139 if (preKeyMetadata
.nextKyberPreKeyId
!= record.getId()) {
1140 logger
.error("Invalid kyber pre key id {}, expected {}",
1142 preKeyMetadata
.nextKyberPreKeyId
);
1143 throw new AssertionError("Invalid kyber pre key id");
1145 accountData
.getKyberPreKeyStore().storeKyberPreKey(record.getId(), record);
1146 preKeyMetadata
.nextKyberPreKeyId
= (preKeyMetadata
.nextKyberPreKeyId
+ 1) % PREKEY_MAXIMUM_ID
;
1151 public void addLastResortKyberPreKey(ServiceIdType serviceIdType
, KyberPreKeyRecord
record) {
1152 final var accountData
= getAccountData(serviceIdType
);
1153 final var preKeyMetadata
= accountData
.getPreKeyMetadata();
1154 logger
.debug("Adding {} last resort kyber pre key with offset {}",
1156 preKeyMetadata
.nextKyberPreKeyId
);
1157 if (preKeyMetadata
.nextKyberPreKeyId
!= record.getId()) {
1158 logger
.error("Invalid last resort kyber pre key id {}, expected {}",
1160 preKeyMetadata
.nextKyberPreKeyId
);
1161 throw new AssertionError("Invalid last resort kyber pre key id");
1163 accountData
.getKyberPreKeyStore().storeLastResortKyberPreKey(record.getId(), record);
1164 preKeyMetadata
.activeLastResortKyberPreKeyId
= record.getId();
1165 preKeyMetadata
.nextKyberPreKeyId
= (preKeyMetadata
.nextKyberPreKeyId
+ 1) % PREKEY_MAXIMUM_ID
;
1169 public int getPreviousStorageVersion() {
1170 return previousStorageVersion
;
1173 public AccountData
<?
extends ServiceId
> getAccountData(ServiceIdType serviceIdType
) {
1174 return switch (serviceIdType
) {
1175 case ACI
-> aciAccountData
;
1176 case PNI
-> pniAccountData
;
1180 public AccountData
<?
extends ServiceId
> getAccountData(ServiceId accountIdentifier
) {
1181 if (accountIdentifier
.equals(aciAccountData
.getServiceId())) {
1182 return aciAccountData
;
1183 } else if (accountIdentifier
.equals(pniAccountData
.getServiceId())) {
1184 return pniAccountData
;
1186 throw new IllegalArgumentException("No matching account data found for " + accountIdentifier
);
1190 public SignalServiceDataStore
getSignalServiceDataStore() {
1191 return new SignalServiceDataStore() {
1193 public SignalServiceAccountDataStore
get(final ServiceId accountIdentifier
) {
1194 return getAccountData(accountIdentifier
).getSignalServiceAccountDataStore();
1198 public SignalServiceAccountDataStore
aci() {
1199 return aciAccountData
.getSignalServiceAccountDataStore();
1203 public SignalServiceAccountDataStore
pni() {
1204 return pniAccountData
.getSignalServiceAccountDataStore();
1208 public boolean isMultiDevice() {
1209 return SignalAccount
.this.isMultiDevice();
1214 public IdentityKeyStore
getIdentityKeyStore() {
1215 return getOrCreate(() -> identityKeyStore
,
1216 () -> identityKeyStore
= new IdentityKeyStore(getAccountDatabase(), settings
.trustNewIdentity()));
1219 public GroupStore
getGroupStore() {
1220 return getOrCreate(() -> groupStore
,
1221 () -> groupStore
= new GroupStore(getAccountDatabase(),
1222 getRecipientResolver(),
1223 getRecipientIdCreator()));
1226 public ContactsStore
getContactStore() {
1227 return getRecipientStore();
1230 public CdsiStore
getCdsiStore() {
1231 return getOrCreate(() -> cdsiStore
, () -> cdsiStore
= new CdsiStore(getAccountDatabase()));
1234 private RecipientIdCreator
getRecipientIdCreator() {
1235 return recipientId
-> getRecipientStore().create(recipientId
);
1238 public RecipientResolver
getRecipientResolver() {
1239 return new RecipientResolver
.RecipientResolverWrapper(this::getRecipientStore
);
1242 public RecipientTrustedResolver
getRecipientTrustedResolver() {
1243 return new RecipientTrustedResolver
.RecipientTrustedResolverWrapper(this::getRecipientStore
);
1246 public RecipientAddressResolver
getRecipientAddressResolver() {
1247 return recipientId
-> getRecipientStore().resolveRecipientAddress(recipientId
);
1250 public RecipientStore
getRecipientStore() {
1251 return getOrCreate(() -> recipientStore
,
1252 () -> recipientStore
= new RecipientStore(this::mergeRecipients
,
1253 this::getSelfRecipientAddress
,
1254 getAccountDatabase()));
1257 public ProfileStore
getProfileStore() {
1258 return getRecipientStore();
1261 public StickerStore
getStickerStore() {
1262 return getOrCreate(() -> stickerStore
, () -> stickerStore
= new StickerStore(getAccountDatabase()));
1265 public SenderKeyStore
getSenderKeyStore() {
1266 return getOrCreate(() -> senderKeyStore
, () -> senderKeyStore
= new SenderKeyStore(getAccountDatabase()));
1269 private KeyValueStore
getKeyValueStore() {
1270 return getOrCreate(() -> keyValueStore
, () -> keyValueStore
= new KeyValueStore(getAccountDatabase()));
1273 public ConfigurationStore
getConfigurationStore() {
1274 return getOrCreate(() -> configurationStore
,
1275 () -> configurationStore
= new ConfigurationStore(getKeyValueStore()));
1278 public MessageCache
getMessageCache() {
1279 return getOrCreate(() -> messageCache
,
1280 () -> messageCache
= new MessageCache(getMessageCachePath(dataPath
, accountPath
)));
1283 public AccountDatabase
getAccountDatabase() {
1284 return getOrCreate(() -> accountDatabase
, () -> {
1286 accountDatabase
= AccountDatabase
.init(getDatabaseFile(dataPath
, accountPath
));
1287 } catch (SQLException e
) {
1288 throw new RuntimeException(e
);
1293 public MessageSendLogStore
getMessageSendLogStore() {
1294 return getOrCreate(() -> messageSendLogStore
,
1295 () -> messageSendLogStore
= new MessageSendLogStore(getAccountDatabase(),
1296 settings
.disableMessageSendLog()));
1299 public CredentialsProvider
getCredentialsProvider() {
1300 return new CredentialsProvider() {
1302 public ACI
getAci() {
1303 return aciAccountData
.getServiceId();
1307 public PNI
getPni() {
1308 return pniAccountData
.getServiceId();
1312 public String
getE164() {
1317 public String
getPassword() {
1322 public int getDeviceId() {
1328 public String
getNumber() {
1332 public void setNumber(final String number
) {
1333 this.number
= number
;
1337 public String
getUsername() {
1341 public void setUsername(final String username
) {
1342 this.username
= username
;
1346 public ServiceEnvironment
getServiceEnvironment() {
1347 return serviceEnvironment
;
1350 public void setServiceEnvironment(final ServiceEnvironment serviceEnvironment
) {
1351 this.serviceEnvironment
= serviceEnvironment
;
1355 public AccountAttributes
getAccountAttributes(String registrationLock
) {
1356 return new AccountAttributes(null,
1357 aciAccountData
.getLocalRegistrationId(),
1361 registrationLock
!= null ? registrationLock
: getRegistrationLock(),
1362 getSelfUnidentifiedAccessKey(),
1363 isUnrestrictedUnidentifiedAccess(),
1364 isDiscoverableByPhoneNumber(),
1365 getAccountCapabilities(),
1366 encryptedDeviceName
,
1367 pniAccountData
.getLocalRegistrationId(),
1368 null); // TODO recoveryPassword?
1371 public AccountAttributes
.Capabilities
getAccountCapabilities() {
1372 return getCapabilities(isPrimaryDevice());
1375 public ServiceId
getAccountId(ServiceIdType serviceIdType
) {
1376 return getAccountData(serviceIdType
).getServiceId();
1379 public ACI
getAci() {
1380 return aciAccountData
.getServiceId();
1383 public void setAci(final ACI aci
) {
1384 this.aciAccountData
.setServiceId(aci
);
1388 public PNI
getPni() {
1389 return pniAccountData
.getServiceId();
1392 public void setPni(final PNI updatedPni
) {
1393 final var oldPni
= pniAccountData
.getServiceId();
1394 if (oldPni
!= null && !oldPni
.equals(updatedPni
)) {
1395 // Clear data for old PNI
1396 identityKeyStore
.deleteIdentity(oldPni
);
1399 this.pniAccountData
.setServiceId(updatedPni
);
1400 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
1401 trustSelfIdentity(ServiceIdType
.PNI
);
1405 public void setNewPniIdentity(
1406 final IdentityKeyPair pniIdentityKeyPair
,
1407 final SignedPreKeyRecord pniSignedPreKey
,
1408 final KyberPreKeyRecord lastResortKyberPreKey
,
1409 final int localPniRegistrationId
1411 setPniIdentityKeyPair(pniIdentityKeyPair
);
1412 pniAccountData
.setLocalRegistrationId(localPniRegistrationId
);
1414 final AccountData
<?
extends ServiceId
> accountData
= getAccountData(ServiceIdType
.PNI
);
1415 final var preKeyMetadata
= accountData
.getPreKeyMetadata();
1416 preKeyMetadata
.nextSignedPreKeyId
= pniSignedPreKey
.getId();
1417 accountData
.getSignedPreKeyStore().removeSignedPreKey(pniSignedPreKey
.getId());
1418 addSignedPreKey(ServiceIdType
.PNI
, pniSignedPreKey
);
1419 if (lastResortKyberPreKey
!= null) {
1420 preKeyMetadata
.nextKyberPreKeyId
= lastResortKyberPreKey
.getId();
1421 accountData
.getKyberPreKeyStore().removeKyberPreKey(lastResortKyberPreKey
.getId());
1422 addLastResortKyberPreKey(ServiceIdType
.PNI
, lastResortKyberPreKey
);
1427 public SignalServiceAddress
getSelfAddress() {
1428 return new SignalServiceAddress(getAci(), number
);
1431 public RecipientAddress
getSelfRecipientAddress() {
1432 return new RecipientAddress(getAci(), getPni(), number
, username
);
1435 public RecipientId
getSelfRecipientId() {
1436 return getRecipientResolver().resolveRecipient(getSelfRecipientAddress());
1439 public String
getSessionId(final String forNumber
) {
1440 final var keyValueStore
= getKeyValueStore();
1441 final var sessionNumber
= keyValueStore
.getEntry(verificationSessionNumber
);
1442 if (!forNumber
.equals(sessionNumber
)) {
1445 return keyValueStore
.getEntry(verificationSessionId
);
1448 public void setSessionId(final String sessionNumber
, final String sessionId
) {
1449 final var keyValueStore
= getKeyValueStore();
1450 keyValueStore
.storeEntry(verificationSessionNumber
, sessionNumber
);
1451 keyValueStore
.storeEntry(verificationSessionId
, sessionId
);
1454 public void setEncryptedDeviceName(final String encryptedDeviceName
) {
1455 this.encryptedDeviceName
= encryptedDeviceName
;
1459 public int getDeviceId() {
1463 public boolean isPrimaryDevice() {
1464 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1467 public IdentityKeyPair
getIdentityKeyPair(ServiceIdType serviceIdType
) {
1468 return getAccountData(serviceIdType
).getIdentityKeyPair();
1471 public IdentityKeyPair
getAciIdentityKeyPair() {
1472 return aciAccountData
.getIdentityKeyPair();
1475 public IdentityKeyPair
getPniIdentityKeyPair() {
1476 return pniAccountData
.getIdentityKeyPair();
1479 public void setPniIdentityKeyPair(final IdentityKeyPair identityKeyPair
) {
1480 pniAccountData
.setIdentityKeyPair(identityKeyPair
);
1481 trustSelfIdentity(ServiceIdType
.PNI
);
1485 public String
getPassword() {
1489 public void setRegistrationLockPin(final String registrationLockPin
) {
1490 this.registrationLockPin
= registrationLockPin
;
1494 public String
getRegistrationLockPin() {
1495 return registrationLockPin
;
1498 public String
getRegistrationLock() {
1499 final var masterKey
= getPinBackedMasterKey();
1500 if (masterKey
== null) {
1503 return masterKey
.deriveRegistrationLock();
1506 public MasterKey
getPinBackedMasterKey() {
1507 if (registrationLockPin
== null) {
1510 return pinMasterKey
;
1513 public MasterKey
getOrCreatePinMasterKey() {
1514 if (pinMasterKey
== null) {
1515 pinMasterKey
= KeyUtils
.createMasterKey();
1518 return pinMasterKey
;
1521 public StorageKey
getStorageKey() {
1522 if (pinMasterKey
!= null) {
1523 return pinMasterKey
.deriveStorageServiceKey();
1528 public StorageKey
getOrCreateStorageKey() {
1529 if (isPrimaryDevice()) {
1530 return getOrCreatePinMasterKey().deriveStorageServiceKey();
1535 public void setStorageKey(final StorageKey storageKey
) {
1536 if (storageKey
.equals(this.storageKey
)) {
1539 this.storageKey
= storageKey
;
1543 public long getStorageManifestVersion() {
1544 return getKeyValueStore().getEntry(storageManifestVersion
);
1547 public void setStorageManifestVersion(final long value
) {
1548 getKeyValueStore().storeEntry(storageManifestVersion
, value
);
1551 public Optional
<SignalStorageManifest
> getStorageManifest() {
1552 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1553 if (!storageManifestFile
.exists()) {
1554 return Optional
.empty();
1556 try (var inputStream
= new FileInputStream(storageManifestFile
)) {
1557 return Optional
.of(SignalStorageManifest
.deserialize(inputStream
.readAllBytes()));
1558 } catch (IOException e
) {
1559 logger
.warn("Failed to read local storage manifest.", e
);
1560 return Optional
.empty();
1564 public void setStorageManifest(SignalStorageManifest manifest
) {
1565 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1566 if (manifest
== null) {
1567 if (storageManifestFile
.exists()) {
1569 Files
.delete(storageManifestFile
.toPath());
1570 } catch (IOException e
) {
1571 logger
.error("Failed to delete local storage manifest.", e
);
1577 final var manifestBytes
= manifest
.serialize();
1578 try (var outputStream
= new FileOutputStream(storageManifestFile
)) {
1579 outputStream
.write(manifestBytes
);
1580 } catch (IOException e
) {
1581 logger
.error("Failed to store local storage manifest.", e
);
1585 public byte[] getCdsiToken() {
1586 return getKeyValueStore().getEntry(cdsiToken
);
1589 public void setCdsiToken(final byte[] value
) {
1590 getKeyValueStore().storeEntry(cdsiToken
, value
);
1593 public Long
getLastRecipientsRefresh() {
1594 return getKeyValueStore().getEntry(lastRecipientsRefresh
);
1597 public void setLastRecipientsRefresh(final Long value
) {
1598 getKeyValueStore().storeEntry(lastRecipientsRefresh
, value
);
1601 public ProfileKey
getProfileKey() {
1605 public void setProfileKey(final ProfileKey profileKey
) {
1606 if (profileKey
.equals(this.profileKey
)) {
1609 this.profileKey
= profileKey
;
1611 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
1614 public byte[] getSelfUnidentifiedAccessKey() {
1615 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
1618 public boolean isRegistered() {
1622 public void setRegistered(final boolean registered
) {
1623 this.registered
= registered
;
1627 public boolean isMultiDevice() {
1628 return isMultiDevice
;
1631 public void setMultiDevice(final boolean multiDevice
) {
1632 if (isMultiDevice
== multiDevice
) {
1635 isMultiDevice
= multiDevice
;
1639 public long getLastReceiveTimestamp() {
1640 return getKeyValueStore().getEntry(lastReceiveTimestamp
);
1643 public void setLastReceiveTimestamp(final long value
) {
1644 getKeyValueStore().storeEntry(lastReceiveTimestamp
, value
);
1647 public boolean isUnrestrictedUnidentifiedAccess() {
1648 final var profile
= getProfileStore().getProfile(getSelfRecipientId());
1649 return profile
!= null && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
;
1652 public boolean isDiscoverableByPhoneNumber() {
1653 final var phoneNumberUnlisted
= getConfigurationStore().getPhoneNumberUnlisted();
1654 return phoneNumberUnlisted
== null || !phoneNumberUnlisted
;
1657 private void trustSelfIdentity(ServiceIdType serviceIdType
) {
1658 final var accountData
= getAccountData(serviceIdType
);
1659 final var serviceId
= accountData
.getServiceId();
1660 final var identityKeyPair
= accountData
.getIdentityKeyPair();
1661 if (serviceId
== null || identityKeyPair
== null) {
1664 final var publicKey
= identityKeyPair
.getPublicKey();
1665 getIdentityKeyStore().saveIdentity(serviceId
, publicKey
);
1666 getIdentityKeyStore().setIdentityTrustLevel(serviceId
, publicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1669 public void deleteAccountData() throws IOException
{
1671 try (final var files
= Files
.walk(getUserPath(dataPath
, accountPath
).toPath())
1672 .sorted(Comparator
.reverseOrder())) {
1673 for (final var file
= files
.iterator(); file
.hasNext(); ) {
1674 Files
.delete(file
.next());
1677 Files
.delete(getFileName(dataPath
, accountPath
).toPath());
1681 public void close() {
1682 synchronized (fileChannel
) {
1683 if (accountDatabase
!= null) {
1685 accountDatabase
.close();
1686 } catch (SQLException e
) {
1687 logger
.warn("Failed to close account database: {}", e
.getMessage(), e
);
1690 if (messageSendLogStore
!= null) {
1691 messageSendLogStore
.close();
1696 } catch (ClosedChannelException ignored
) {
1698 fileChannel
.close();
1699 } catch (IOException e
) {
1700 logger
.warn("Failed to close account: {}", e
.getMessage(), e
);
1705 private <T
> T
getOrCreate(Supplier
<T
> supplier
, Callable creator
) {
1706 var value
= supplier
.get();
1707 if (value
!= null) {
1711 synchronized (LOCK
) {
1712 value
= supplier
.get();
1713 if (value
!= null) {
1717 return supplier
.get();
1721 private interface Callable
{
1726 public static class PreKeyMetadata
{
1728 private int nextPreKeyId
= 1;
1729 private int nextSignedPreKeyId
= 1;
1730 private int activeSignedPreKeyId
= -1;
1731 private int nextKyberPreKeyId
= 1;
1732 private int activeLastResortKyberPreKeyId
= -1;
1734 public int getNextPreKeyId() {
1735 return nextPreKeyId
;
1738 public int getNextSignedPreKeyId() {
1739 return nextSignedPreKeyId
;
1742 public int getActiveSignedPreKeyId() {
1743 return activeSignedPreKeyId
;
1746 public int getNextKyberPreKeyId() {
1747 return nextKyberPreKeyId
;
1750 public int getActiveLastResortKyberPreKeyId() {
1751 return activeLastResortKyberPreKeyId
;
1755 public class AccountData
<SERVICE_ID
extends ServiceId
> {
1757 private final ServiceIdType serviceIdType
;
1758 private SERVICE_ID serviceId
;
1759 private IdentityKeyPair identityKeyPair
;
1760 private int localRegistrationId
;
1761 private final PreKeyMetadata preKeyMetadata
= new PreKeyMetadata();
1763 private SignalProtocolStore signalProtocolStore
;
1764 private PreKeyStore preKeyStore
;
1765 private SignedPreKeyStore signedPreKeyStore
;
1766 private KyberPreKeyStore kyberPreKeyStore
;
1767 private SessionStore sessionStore
;
1768 private SignalIdentityKeyStore identityKeyStore
;
1770 private AccountData(final ServiceIdType serviceIdType
) {
1771 this.serviceIdType
= serviceIdType
;
1774 public SERVICE_ID
getServiceId() {
1778 private void setServiceId(final SERVICE_ID serviceId
) {
1779 this.serviceId
= serviceId
;
1782 public IdentityKeyPair
getIdentityKeyPair() {
1783 return identityKeyPair
;
1786 private void setIdentityKeyPair(final IdentityKeyPair identityKeyPair
) {
1787 this.identityKeyPair
= identityKeyPair
;
1790 public int getLocalRegistrationId() {
1791 return localRegistrationId
;
1794 private void setLocalRegistrationId(final int localRegistrationId
) {
1795 this.localRegistrationId
= localRegistrationId
;
1796 this.identityKeyStore
= null;
1799 public PreKeyMetadata
getPreKeyMetadata() {
1800 return preKeyMetadata
;
1803 private SignalServiceAccountDataStore
getSignalServiceAccountDataStore() {
1804 return getOrCreate(() -> signalProtocolStore
,
1805 () -> signalProtocolStore
= new SignalProtocolStore(getPreKeyStore(),
1806 getSignedPreKeyStore(),
1807 getKyberPreKeyStore(),
1809 getIdentityKeyStore(),
1810 getSenderKeyStore(),
1811 SignalAccount
.this::isMultiDevice
));
1814 public PreKeyStore
getPreKeyStore() {
1815 return getOrCreate(() -> preKeyStore
,
1816 () -> preKeyStore
= new PreKeyStore(getAccountDatabase(), serviceIdType
));
1819 public SignedPreKeyStore
getSignedPreKeyStore() {
1820 return getOrCreate(() -> signedPreKeyStore
,
1821 () -> signedPreKeyStore
= new SignedPreKeyStore(getAccountDatabase(), serviceIdType
));
1824 public KyberPreKeyStore
getKyberPreKeyStore() {
1825 return getOrCreate(() -> kyberPreKeyStore
,
1826 () -> kyberPreKeyStore
= new KyberPreKeyStore(getAccountDatabase(), serviceIdType
));
1829 public SessionStore
getSessionStore() {
1830 return getOrCreate(() -> sessionStore
,
1831 () -> sessionStore
= new SessionStore(getAccountDatabase(), serviceIdType
));
1834 public SignalIdentityKeyStore
getIdentityKeyStore() {
1835 return getOrCreate(() -> identityKeyStore
,
1836 () -> identityKeyStore
= new SignalIdentityKeyStore(() -> identityKeyPair
,
1837 localRegistrationId
,
1838 SignalAccount
.this.getIdentityKeyStore()));
1842 public record Storage(
1844 String serviceEnvironment
,
1848 String encryptedDeviceName
,
1850 boolean isMultiDevice
,
1852 AccountData aciAccountData
,
1853 AccountData pniAccountData
,
1854 String registrationLockPin
,
1855 String pinMasterKey
,
1860 public record AccountData(
1863 String identityPrivateKey
,
1864 String identityPublicKey
,
1867 int nextSignedPreKeyId
,
1868 int activeSignedPreKeyId
,
1869 int nextKyberPreKeyId
,
1870 int activeLastResortKyberPreKeyId
1873 private static AccountData
from(final SignalAccount
.AccountData
<?
> accountData
) {
1874 final var base64
= Base64
.getEncoder();
1875 final var preKeyMetadata
= accountData
.getPreKeyMetadata();
1876 return new AccountData(accountData
.getServiceId() == null
1878 : accountData
.getServiceId().toString(),
1879 accountData
.getLocalRegistrationId(),
1880 accountData
.getIdentityKeyPair() == null
1882 : base64
.encodeToString(accountData
.getIdentityKeyPair().getPrivateKey().serialize()),
1883 accountData
.getIdentityKeyPair() == null
1885 : base64
.encodeToString(accountData
.getIdentityKeyPair().getPublicKey().serialize()),
1886 preKeyMetadata
.getNextPreKeyId(),
1887 preKeyMetadata
.getNextSignedPreKeyId(),
1888 preKeyMetadata
.getActiveSignedPreKeyId(),
1889 preKeyMetadata
.getNextKyberPreKeyId(),
1890 preKeyMetadata
.getActiveLastResortKyberPreKeyId());