diff --git a/examples/platform/linux/testing/CustomCSRResponseOperationalKeyStore.cpp b/examples/platform/linux/testing/CustomCSRResponseOperationalKeyStore.cpp index cbdb3802f80813..1cc4797b286359 100644 --- a/examples/platform/linux/testing/CustomCSRResponseOperationalKeyStore.cpp +++ b/examples/platform/linux/testing/CustomCSRResponseOperationalKeyStore.cpp @@ -68,11 +68,10 @@ CHIP_ERROR CustomCSRResponseOperationalKeyStore::ReuseOpKeypair(FabricIndex fabr // Load up the operational key structure from storage uint16_t size = static_cast(buf.Capacity()); - DefaultStorageKeyAllocator keyAlloc; // In order to retrieve a keypair that has already been registered, assume the device // as already been commissioned and fabric index 1 is the registered fabric. - CHIP_ERROR err = mStorage->SyncGetKeyValue(keyAlloc.FabricOpKey(1 /* fabricIndex */), buf.Bytes(), size); + CHIP_ERROR err = mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::FabricOpKey(1 /* fabricIndex */), buf.Bytes(), size); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { err = CHIP_ERROR_INVALID_FABRIC_INDEX; diff --git a/examples/providers/DeviceInfoProviderImpl.cpp b/examples/providers/DeviceInfoProviderImpl.cpp index 74245d93da81d4..fb339895dede9e 100644 --- a/examples/providers/DeviceInfoProviderImpl.cpp +++ b/examples/providers/DeviceInfoProviderImpl.cpp @@ -120,24 +120,21 @@ bool DeviceInfoProviderImpl::FixedLabelIteratorImpl::Next(FixedLabelType & outpu CHIP_ERROR DeviceInfoProviderImpl::SetUserLabelLength(EndpointId endpoint, size_t val) { - DefaultStorageKeyAllocator keyAlloc; - - return mStorage->SyncSetKeyValue(keyAlloc.UserLabelLengthKey(endpoint), &val, static_cast(sizeof(val))); + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::UserLabelLengthKey(endpoint), &val, + static_cast(sizeof(val))); } CHIP_ERROR DeviceInfoProviderImpl::GetUserLabelLength(EndpointId endpoint, size_t & val) { - DefaultStorageKeyAllocator keyAlloc; uint16_t len = static_cast(sizeof(val)); - return mStorage->SyncGetKeyValue(keyAlloc.UserLabelLengthKey(endpoint), &val, len); + return mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::UserLabelLengthKey(endpoint), &val, len); } CHIP_ERROR DeviceInfoProviderImpl::SetUserLabelAt(EndpointId endpoint, size_t index, const UserLabelType & userLabel) { VerifyOrReturnError(CanCastTo(index), CHIP_ERROR_INVALID_ARGUMENT); - DefaultStorageKeyAllocator keyAlloc; uint8_t buf[UserLabelTLVMaxSize()]; TLV::TLVWriter writer; writer.Init(buf); @@ -148,15 +145,13 @@ CHIP_ERROR DeviceInfoProviderImpl::SetUserLabelAt(EndpointId endpoint, size_t in ReturnErrorOnFailure(writer.PutString(kLabelValueTag, userLabel.value)); ReturnErrorOnFailure(writer.EndContainer(outerType)); - return mStorage->SyncSetKeyValue(keyAlloc.UserLabelIndexKey(endpoint, static_cast(index)), buf, + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::UserLabelIndexKey(endpoint, static_cast(index)), buf, static_cast(writer.GetLengthWritten())); } CHIP_ERROR DeviceInfoProviderImpl::DeleteUserLabelAt(EndpointId endpoint, size_t index) { - DefaultStorageKeyAllocator keyAlloc; - - return mStorage->SyncDeleteKeyValue(keyAlloc.UserLabelIndexKey(endpoint, static_cast(index))); + return mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::UserLabelIndexKey(endpoint, static_cast(index))); } DeviceInfoProvider::UserLabelIterator * DeviceInfoProviderImpl::IterateUserLabel(EndpointId endpoint) @@ -181,11 +176,11 @@ bool DeviceInfoProviderImpl::UserLabelIteratorImpl::Next(UserLabelType & output) VerifyOrReturnError(mIndex < mTotal, false); VerifyOrReturnError(CanCastTo(mIndex), false); - DefaultStorageKeyAllocator keyAlloc; uint8_t buf[UserLabelTLVMaxSize()]; uint16_t len = static_cast(sizeof(buf)); - err = mProvider.mStorage->SyncGetKeyValue(keyAlloc.UserLabelIndexKey(mEndpoint, static_cast(mIndex)), buf, len); + err = mProvider.mStorage->SyncGetKeyValue( + DefaultStorageKeyAllocator::UserLabelIndexKey(mEndpoint, static_cast(mIndex)), buf, len); VerifyOrReturnError(err == CHIP_NO_ERROR, false); TLV::ContiguousBufferTLVReader reader; diff --git a/src/app/DefaultAttributePersistenceProvider.cpp b/src/app/DefaultAttributePersistenceProvider.cpp index 502b28e914d638..40e973f58b218d 100644 --- a/src/app/DefaultAttributePersistenceProvider.cpp +++ b/src/app/DefaultAttributePersistenceProvider.cpp @@ -30,13 +30,13 @@ CHIP_ERROR DefaultAttributePersistenceProvider::WriteValue(const ConcreteAttribu // TODO: we may want to have a small cache for values that change a lot, so // we only write them once a bunch of changes happen or on timer or // shutdown. - DefaultStorageKeyAllocator key; if (!CanCastTo(aValue.size())) { return CHIP_ERROR_BUFFER_TOO_SMALL; } - return mStorage->SyncSetKeyValue(key.AttributeValue(aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId), aValue.data(), - static_cast(aValue.size())); + return mStorage->SyncSetKeyValue( + DefaultStorageKeyAllocator::AttributeValue(aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId), aValue.data(), + static_cast(aValue.size())); } CHIP_ERROR DefaultAttributePersistenceProvider::ReadValue(const ConcreteAttributePath & aPath, @@ -44,10 +44,9 @@ CHIP_ERROR DefaultAttributePersistenceProvider::ReadValue(const ConcreteAttribut { VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); - DefaultStorageKeyAllocator key; uint16_t size = static_cast(min(aValue.size(), static_cast(UINT16_MAX))); - ReturnErrorOnFailure(mStorage->SyncGetKeyValue(key.AttributeValue(aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId), - aValue.data(), size)); + ReturnErrorOnFailure(mStorage->SyncGetKeyValue( + DefaultStorageKeyAllocator::AttributeValue(aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId), aValue.data(), size)); EmberAfAttributeType type = aMetadata->attributeType; if (emberAfIsStringAttributeType(type)) { diff --git a/src/app/clusters/access-control-server/access-control-server.cpp b/src/app/clusters/access-control-server/access-control-server.cpp index 3e3122390c8abb..8fed6a010cbbad 100644 --- a/src/app/clusters/access-control-server/access-control-server.cpp +++ b/src/app/clusters/access-control-server/access-control-server.cpp @@ -192,8 +192,6 @@ CHIP_ERROR AccessControlAttribute::ReadAcl(AttributeValueEncoder & aEncoder) CHIP_ERROR AccessControlAttribute::ReadExtension(AttributeValueEncoder & aEncoder) { auto & storage = Server::GetInstance().GetPersistentStorage(); - DefaultStorageKeyAllocator key; - auto & fabrics = Server::GetInstance().GetFabricTable(); return aEncoder.EncodeList([&](const auto & encoder) -> CHIP_ERROR { @@ -201,7 +199,8 @@ CHIP_ERROR AccessControlAttribute::ReadExtension(AttributeValueEncoder & aEncode { uint8_t buffer[kExtensionDataMaxLength] = { 0 }; uint16_t size = static_cast(sizeof(buffer)); - CHIP_ERROR errStorage = storage.SyncGetKeyValue(key.AccessControlExtensionEntry(fabric.GetFabricIndex()), buffer, size); + CHIP_ERROR errStorage = storage.SyncGetKeyValue( + DefaultStorageKeyAllocator::AccessControlExtensionEntry(fabric.GetFabricIndex()), buffer, size); ReturnErrorCodeIf(errStorage == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_ERROR_INCORRECT_STATE); if (errStorage == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { @@ -295,13 +294,13 @@ CHIP_ERROR AccessControlAttribute::WriteAcl(const ConcreteDataAttributePath & aP CHIP_ERROR AccessControlAttribute::WriteExtension(const ConcreteDataAttributePath & aPath, AttributeValueDecoder & aDecoder) { auto & storage = Server::GetInstance().GetPersistentStorage(); - DefaultStorageKeyAllocator key; FabricIndex accessingFabricIndex = aDecoder.AccessingFabricIndex(); uint8_t buffer[kExtensionDataMaxLength] = { 0 }; uint16_t size = static_cast(sizeof(buffer)); - CHIP_ERROR errStorage = storage.SyncGetKeyValue(key.AccessControlExtensionEntry(accessingFabricIndex), buffer, size); + CHIP_ERROR errStorage = + storage.SyncGetKeyValue(DefaultStorageKeyAllocator::AccessControlExtensionEntry(accessingFabricIndex), buffer, size); ReturnErrorCodeIf(errStorage == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(errStorage != CHIP_NO_ERROR && errStorage != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, errStorage); @@ -316,7 +315,8 @@ CHIP_ERROR AccessControlAttribute::WriteExtension(const ConcreteDataAttributePat if (count == 0) { ReturnErrorCodeIf(errStorage == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR); - ReturnErrorOnFailure(storage.SyncDeleteKeyValue(key.AccessControlExtensionEntry(accessingFabricIndex))); + ReturnErrorOnFailure( + storage.SyncDeleteKeyValue(DefaultStorageKeyAllocator::AccessControlExtensionEntry(accessingFabricIndex))); AccessControlCluster::Structs::ExtensionEntry::Type item = { .data = ByteSpan(buffer, size), .fabricIndex = accessingFabricIndex, @@ -339,8 +339,9 @@ CHIP_ERROR AccessControlAttribute::WriteExtension(const ConcreteDataAttributePat ReturnErrorOnFailure(CheckExtensionEntryDataFormat(item.data)); - ReturnErrorOnFailure(storage.SyncSetKeyValue(key.AccessControlExtensionEntry(accessingFabricIndex), item.data.data(), - static_cast(item.data.size()))); + ReturnErrorOnFailure( + storage.SyncSetKeyValue(DefaultStorageKeyAllocator::AccessControlExtensionEntry(accessingFabricIndex), + item.data.data(), static_cast(item.data.size()))); ReturnErrorOnFailure(LogExtensionChangedEvent(item, aDecoder.GetSubjectDescriptor(), errStorage == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND ? AccessControlCluster::ChangeTypeEnum::kAdded @@ -361,8 +362,8 @@ CHIP_ERROR AccessControlAttribute::WriteExtension(const ConcreteDataAttributePat ReturnErrorOnFailure(CheckExtensionEntryDataFormat(item.data)); - ReturnErrorOnFailure(storage.SyncSetKeyValue(key.AccessControlExtensionEntry(accessingFabricIndex), item.data.data(), - static_cast(item.data.size()))); + ReturnErrorOnFailure(storage.SyncSetKeyValue(DefaultStorageKeyAllocator::AccessControlExtensionEntry(accessingFabricIndex), + item.data.data(), static_cast(item.data.size()))); ReturnErrorOnFailure( LogExtensionChangedEvent(item, aDecoder.GetSubjectDescriptor(), AccessControlCluster::ChangeTypeEnum::kAdded)); } diff --git a/src/app/clusters/ota-requestor/DefaultOTARequestorStorage.cpp b/src/app/clusters/ota-requestor/DefaultOTARequestorStorage.cpp index f79eac7fc1070e..07220d12d00024 100644 --- a/src/app/clusters/ota-requestor/DefaultOTARequestorStorage.cpp +++ b/src/app/clusters/ota-requestor/DefaultOTARequestorStorage.cpp @@ -40,7 +40,6 @@ constexpr size_t kProviderListMaxSerializedSize = kProviderMaxSerializedSize * C CHIP_ERROR DefaultOTARequestorStorage::StoreDefaultProviders(const ProviderLocationList & providers) { - DefaultStorageKeyAllocator key; uint8_t buffer[kProviderListMaxSerializedSize]; TLV::TLVWriter writer; TLV::TLVType outerType; @@ -56,16 +55,16 @@ CHIP_ERROR DefaultOTARequestorStorage::StoreDefaultProviders(const ProviderLocat ReturnErrorOnFailure(writer.EndContainer(outerType)); - return mPersistentStorage->SyncSetKeyValue(key.OTADefaultProviders(), buffer, static_cast(writer.GetLengthWritten())); + return mPersistentStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::OTADefaultProviders(), buffer, + static_cast(writer.GetLengthWritten())); } CHIP_ERROR DefaultOTARequestorStorage::LoadDefaultProviders(ProviderLocationList & providers) { - DefaultStorageKeyAllocator key; uint8_t buffer[kProviderListMaxSerializedSize]; MutableByteSpan bufferSpan(buffer); - ReturnErrorOnFailure(Load(key.OTADefaultProviders(), bufferSpan)); + ReturnErrorOnFailure(Load(DefaultStorageKeyAllocator::OTADefaultProviders(), bufferSpan)); TLV::TLVReader reader; TLV::TLVType outerType; @@ -88,30 +87,27 @@ CHIP_ERROR DefaultOTARequestorStorage::LoadDefaultProviders(ProviderLocationList CHIP_ERROR DefaultOTARequestorStorage::StoreCurrentProviderLocation(const ProviderLocationType & provider) { - DefaultStorageKeyAllocator key; uint8_t buffer[kProviderMaxSerializedSize]; TLV::TLVWriter writer; writer.Init(buffer); ReturnErrorOnFailure(provider.EncodeForRead(writer, TLV::AnonymousTag(), provider.fabricIndex)); - return mPersistentStorage->SyncSetKeyValue(key.OTACurrentProvider(), buffer, static_cast(writer.GetLengthWritten())); + return mPersistentStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::OTACurrentProvider(), buffer, + static_cast(writer.GetLengthWritten())); } CHIP_ERROR DefaultOTARequestorStorage::ClearCurrentProviderLocation() { - DefaultStorageKeyAllocator key; - - return mPersistentStorage->SyncDeleteKeyValue(key.OTACurrentProvider()); + return mPersistentStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::OTACurrentProvider()); } CHIP_ERROR DefaultOTARequestorStorage::LoadCurrentProviderLocation(ProviderLocationType & provider) { - DefaultStorageKeyAllocator key; uint8_t buffer[kProviderMaxSerializedSize]; MutableByteSpan bufferSpan(buffer); - ReturnErrorOnFailure(Load(key.OTACurrentProvider(), bufferSpan)); + ReturnErrorOnFailure(Load(DefaultStorageKeyAllocator::OTACurrentProvider(), bufferSpan)); TLV::TLVReader reader; @@ -124,67 +120,54 @@ CHIP_ERROR DefaultOTARequestorStorage::LoadCurrentProviderLocation(ProviderLocat CHIP_ERROR DefaultOTARequestorStorage::StoreUpdateToken(ByteSpan updateToken) { - DefaultStorageKeyAllocator key; - - return mPersistentStorage->SyncSetKeyValue(key.OTAUpdateToken(), updateToken.data(), static_cast(updateToken.size())); + return mPersistentStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::OTAUpdateToken(), updateToken.data(), + static_cast(updateToken.size())); } CHIP_ERROR DefaultOTARequestorStorage::ClearUpdateToken() { - DefaultStorageKeyAllocator key; - - return mPersistentStorage->SyncDeleteKeyValue(key.OTAUpdateToken()); + return mPersistentStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::OTAUpdateToken()); } CHIP_ERROR DefaultOTARequestorStorage::LoadUpdateToken(MutableByteSpan & updateToken) { - DefaultStorageKeyAllocator key; - - return Load(key.OTAUpdateToken(), updateToken); + return Load(DefaultStorageKeyAllocator::OTAUpdateToken(), updateToken); } CHIP_ERROR DefaultOTARequestorStorage::StoreCurrentUpdateState(OTAUpdateStateEnum currentUpdateState) { - DefaultStorageKeyAllocator key; - - return mPersistentStorage->SyncSetKeyValue(key.OTACurrentUpdateState(), ¤tUpdateState, sizeof(currentUpdateState)); + return mPersistentStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::OTACurrentUpdateState(), ¤tUpdateState, + sizeof(currentUpdateState)); } CHIP_ERROR DefaultOTARequestorStorage::LoadCurrentUpdateState(OTAUpdateStateEnum & currentUpdateState) { - DefaultStorageKeyAllocator key; uint16_t size = static_cast(sizeof(currentUpdateState)); - return mPersistentStorage->SyncGetKeyValue(key.OTACurrentUpdateState(), ¤tUpdateState, size); + return mPersistentStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::OTACurrentUpdateState(), ¤tUpdateState, size); } CHIP_ERROR DefaultOTARequestorStorage::ClearCurrentUpdateState() { - DefaultStorageKeyAllocator key; - - return mPersistentStorage->SyncDeleteKeyValue(key.OTACurrentUpdateState()); + return mPersistentStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::OTACurrentUpdateState()); } CHIP_ERROR DefaultOTARequestorStorage::StoreTargetVersion(uint32_t targetVersion) { - DefaultStorageKeyAllocator key; - - return mPersistentStorage->SyncSetKeyValue(key.OTATargetVersion(), &targetVersion, sizeof(targetVersion)); + return mPersistentStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::OTATargetVersion(), &targetVersion, + sizeof(targetVersion)); } CHIP_ERROR DefaultOTARequestorStorage::LoadTargetVersion(uint32_t & targetVersion) { - DefaultStorageKeyAllocator key; uint16_t size = static_cast(sizeof(targetVersion)); - return mPersistentStorage->SyncGetKeyValue(key.OTATargetVersion(), &targetVersion, size); + return mPersistentStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::OTATargetVersion(), &targetVersion, size); } CHIP_ERROR DefaultOTARequestorStorage::ClearTargetVersion() { - DefaultStorageKeyAllocator key; - - return mPersistentStorage->SyncDeleteKeyValue(key.OTATargetVersion()); + return mPersistentStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::OTATargetVersion()); } CHIP_ERROR DefaultOTARequestorStorage::Load(const char * key, MutableByteSpan & buffer) diff --git a/src/app/server/DefaultAclStorage.cpp b/src/app/server/DefaultAclStorage.cpp index f80a112ba93ea7..244482557b63a9 100644 --- a/src/app/server/DefaultAclStorage.cpp +++ b/src/app/server/DefaultAclStorage.cpp @@ -75,8 +75,6 @@ class : public EntryListener { CHIP_ERROR err; - DefaultStorageKeyAllocator key; - uint8_t buffer[kEncodedEntryTotalBytes] = { 0 }; VerifyOrExit(mPersistentStorage != nullptr, err = CHIP_ERROR_INCORRECT_STATE); @@ -87,16 +85,19 @@ class : public EntryListener while (true) { uint16_t size = static_cast(sizeof(buffer)); - err = mPersistentStorage->SyncGetKeyValue(key.AccessControlAclEntry(fabric, index + 1), buffer, size); + err = mPersistentStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::AccessControlAclEntry(fabric, index + 1), + buffer, size); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { break; } SuccessOrExit(err); - SuccessOrExit(err = mPersistentStorage->SyncSetKeyValue(key.AccessControlAclEntry(fabric, index), buffer, size)); + SuccessOrExit(err = mPersistentStorage->SyncSetKeyValue( + DefaultStorageKeyAllocator::AccessControlAclEntry(fabric, index), buffer, size)); index++; } - SuccessOrExit(err = mPersistentStorage->SyncDeleteKeyValue(key.AccessControlAclEntry(fabric, index))); + SuccessOrExit( + err = mPersistentStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::AccessControlAclEntry(fabric, index))); } else { @@ -106,8 +107,9 @@ class : public EntryListener writer.Init(buffer); EncodableEntry encodableEntry(*entry); SuccessOrExit(err = encodableEntry.EncodeForWrite(writer, TLV::AnonymousTag())); - SuccessOrExit(err = mPersistentStorage->SyncSetKeyValue(key.AccessControlAclEntry(fabric, index), buffer, - static_cast(writer.GetLengthWritten()))); + SuccessOrExit(err = + mPersistentStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::AccessControlAclEntry(fabric, index), + buffer, static_cast(writer.GetLengthWritten()))); } return; @@ -136,8 +138,6 @@ CHIP_ERROR DefaultAclStorage::Init(PersistentStorageDelegate & persistentStorage CHIP_ERROR err; - DefaultStorageKeyAllocator key; - size_t count = 0; for (auto it = first; it != last; ++it) @@ -147,7 +147,7 @@ CHIP_ERROR DefaultAclStorage::Init(PersistentStorageDelegate & persistentStorage { uint8_t buffer[kEncodedEntryTotalBytes] = { 0 }; uint16_t size = static_cast(sizeof(buffer)); - err = persistentStorage.SyncGetKeyValue(key.AccessControlAclEntry(fabric, index), buffer, size); + err = persistentStorage.SyncGetKeyValue(DefaultStorageKeyAllocator::AccessControlAclEntry(fabric, index), buffer, size); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { break; diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index a3a2b49d70eb46..3705cb47d3212c 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -225,7 +225,7 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams) #if CHIP_CONFIG_ENABLE_SERVER_IM_EVENT // Initialize event logging subsystem - err = sGlobalEventIdCounter.Init(mDeviceStorage, &DefaultStorageKeyAllocator::IMEventNumber, + err = sGlobalEventIdCounter.Init(mDeviceStorage, DefaultStorageKeyAllocator::IMEventNumber(), CHIP_DEVICE_CONFIG_EVENT_ID_COUNTER_EPOCH); SuccessOrExit(err); diff --git a/src/app/server/Server.h b/src/app/server/Server.h index 7e1419e50c320c..25b093e192e4f5 100644 --- a/src/app/server/Server.h +++ b/src/app/server/Server.h @@ -446,8 +446,7 @@ class Server // Remove ACL extension entry for the given fabricIndex. auto & storage = mServer->GetPersistentStorage(); - DefaultStorageKeyAllocator key; - aclErr = storage.SyncDeleteKeyValue(key.AccessControlExtensionEntry(fabricIndex)); + aclErr = storage.SyncDeleteKeyValue(DefaultStorageKeyAllocator::AccessControlExtensionEntry(fabricIndex)); if (aclErr != CHIP_NO_ERROR && aclErr != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { diff --git a/src/app/tests/TestBindingTable.cpp b/src/app/tests/TestBindingTable.cpp index c1a3e6e23a39b6..d9e4c84d68dd43 100644 --- a/src/app/tests/TestBindingTable.cpp +++ b/src/app/tests/TestBindingTable.cpp @@ -134,7 +134,6 @@ void TestPersistentStorage(nlTestSuite * aSuite, void * aContext) { chip::TestPersistentStorageDelegate testStorage; BindingTable table; - chip::DefaultStorageKeyAllocator key; chip::Optional cluster = chip::MakeOptional(static_cast(UINT16_MAX + 6)); std::vector expected = { EmberBindingTableEntry::ForNode(0, 0, 0, 0, NullOptional), @@ -150,13 +149,13 @@ void TestPersistentStorage(nlTestSuite * aSuite, void * aContext) VerifyRestored(aSuite, testStorage, expected); // Verify storage untouched if add fails - testStorage.AddPoisonKey(key.BindingTableEntry(4)); + testStorage.AddPoisonKey(chip::DefaultStorageKeyAllocator::BindingTableEntry(4).KeyName()); NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(4, 4, 0, 0, NullOptional)) != CHIP_NO_ERROR); VerifyRestored(aSuite, testStorage, expected); testStorage.ClearPoisonKeys(); // Verify storage untouched if removing head fails - testStorage.AddPoisonKey(key.BindingTable()); + testStorage.AddPoisonKey(chip::DefaultStorageKeyAllocator::BindingTable().KeyName()); auto iter = table.begin(); NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) != CHIP_NO_ERROR); VerifyTableSame(aSuite, table, expected); @@ -164,7 +163,7 @@ void TestPersistentStorage(nlTestSuite * aSuite, void * aContext) VerifyRestored(aSuite, testStorage, expected); // Verify storage untouched if removing other nodes fails - testStorage.AddPoisonKey(key.BindingTableEntry(0)); + testStorage.AddPoisonKey(chip::DefaultStorageKeyAllocator::BindingTableEntry(0).KeyName()); iter = table.begin(); ++iter; NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) != CHIP_NO_ERROR); diff --git a/src/app/util/binding-table.cpp b/src/app/util/binding-table.cpp index 64abcc6175d025..76192cdb12610b 100644 --- a/src/app/util/binding-table.cpp +++ b/src/app/util/binding-table.cpp @@ -55,7 +55,7 @@ CHIP_ERROR BindingTable::Add(const EmberBindingTableEntry & entry) } if (error != CHIP_NO_ERROR) { - mStorage->SyncDeleteKeyValue(mKeyAllocator.BindingTableEntry(newIndex)); + mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::BindingTableEntry(newIndex)); } } if (error != CHIP_NO_ERROR) @@ -112,7 +112,7 @@ CHIP_ERROR BindingTable::SaveEntryToStorage(uint8_t index, uint8_t nextIndex) ReturnErrorOnFailure(writer.Put(TLV::ContextTag(kTagNextEntry), nextIndex)); ReturnErrorOnFailure(writer.EndContainer(container)); ReturnErrorOnFailure(writer.Finalize()); - return mStorage->SyncSetKeyValue(mKeyAllocator.BindingTableEntry(index), buffer, + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::BindingTableEntry(index), buffer, static_cast(writer.GetLengthWritten())); } @@ -127,7 +127,8 @@ CHIP_ERROR BindingTable::SaveListInfo(uint8_t head) ReturnErrorOnFailure(writer.Put(TLV::ContextTag(kTagHead), head)); ReturnErrorOnFailure(writer.EndContainer(container)); ReturnErrorOnFailure(writer.Finalize()); - return mStorage->SyncSetKeyValue(mKeyAllocator.BindingTable(), buffer, static_cast(writer.GetLengthWritten())); + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::BindingTable(), buffer, + static_cast(writer.GetLengthWritten())); } CHIP_ERROR BindingTable::LoadFromStorage() @@ -137,7 +138,7 @@ CHIP_ERROR BindingTable::LoadFromStorage() uint16_t size = sizeof(buffer); CHIP_ERROR error; - ReturnErrorOnFailure(mStorage->SyncGetKeyValue(mKeyAllocator.BindingTable(), buffer, size)); + ReturnErrorOnFailure(mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::BindingTable(), buffer, size)); TLV::TLVReader reader; reader.Init(buffer, size); @@ -183,7 +184,7 @@ CHIP_ERROR BindingTable::LoadEntryFromStorage(uint8_t index, uint8_t & nextIndex uint16_t size = sizeof(buffer); EmberBindingTableEntry entry; - ReturnErrorOnFailure(mStorage->SyncGetKeyValue(mKeyAllocator.BindingTableEntry(index), buffer, size)); + ReturnErrorOnFailure(mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::BindingTableEntry(index), buffer, size)); TLV::TLVReader reader; reader.Init(buffer, size); @@ -259,7 +260,7 @@ CHIP_ERROR BindingTable::RemoveAt(Iterator & iter) if (error == CHIP_NO_ERROR) { // The remove is considered "submitted" once the change on prev node takes effect - if (mStorage->SyncDeleteKeyValue(mKeyAllocator.BindingTableEntry(iter.mIndex)) != CHIP_NO_ERROR) + if (mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::BindingTableEntry(iter.mIndex)) != CHIP_NO_ERROR) { ChipLogError(AppServer, "Failed to remove binding table entry %u from storage", iter.mIndex); } diff --git a/src/app/util/binding-table.h b/src/app/util/binding-table.h index 792a796b737356..d6aa4d7f440ceb 100644 --- a/src/app/util/binding-table.h +++ b/src/app/util/binding-table.h @@ -117,7 +117,6 @@ class BindingTable uint8_t mSize = 0; PersistentStorageDelegate * mStorage; - DefaultStorageKeyAllocator mKeyAllocator; }; } // namespace chip diff --git a/src/credentials/FabricTable.cpp b/src/credentials/FabricTable.cpp index 1bb3b8b0139ef2..01a593084455c4 100644 --- a/src/credentials/FabricTable.cpp +++ b/src/credentials/FabricTable.cpp @@ -124,8 +124,6 @@ void FabricInfo::operator=(FabricInfo && other) CHIP_ERROR FabricInfo::CommitToStorage(PersistentStorageDelegate * storage) const { - DefaultStorageKeyAllocator keyAlloc; - { uint8_t buf[MetadataTLVMaxSize()]; TLV::TLVWriter writer; @@ -142,8 +140,8 @@ CHIP_ERROR FabricInfo::CommitToStorage(PersistentStorageDelegate * storage) cons const auto metadataLength = writer.GetLengthWritten(); VerifyOrReturnError(CanCastTo(metadataLength), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorOnFailure( - storage->SyncSetKeyValue(keyAlloc.FabricMetadata(mFabricIndex), buf, static_cast(metadataLength))); + ReturnErrorOnFailure(storage->SyncSetKeyValue(DefaultStorageKeyAllocator::FabricMetadata(mFabricIndex), buf, + static_cast(metadataLength))); } // NOTE: Operational Key is never saved to storage here. See OperationalKeystore interface for how it is accessed @@ -154,8 +152,6 @@ CHIP_ERROR FabricInfo::CommitToStorage(PersistentStorageDelegate * storage) cons CHIP_ERROR FabricInfo::LoadFromStorage(PersistentStorageDelegate * storage, FabricIndex newFabricIndex, const ByteSpan & rcac, const ByteSpan & noc) { - DefaultStorageKeyAllocator keyAlloc; - mFabricIndex = newFabricIndex; // Regenerate operational metadata from NOC/RCAC @@ -179,7 +175,7 @@ CHIP_ERROR FabricInfo::LoadFromStorage(PersistentStorageDelegate * storage, Fabr { uint8_t buf[MetadataTLVMaxSize()]; uint16_t size = sizeof(buf); - ReturnErrorOnFailure(storage->SyncGetKeyValue(keyAlloc.FabricMetadata(mFabricIndex), buf, size)); + ReturnErrorOnFailure(storage->SyncGetKeyValue(DefaultStorageKeyAllocator::FabricMetadata(mFabricIndex), buf, size)); TLV::ContiguousBufferTLVReader reader; reader.Init(buf, size); @@ -218,8 +214,7 @@ CHIP_ERROR FabricTable::DeleteMetadataFromStorage(FabricIndex fabricIndex) VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); - DefaultStorageKeyAllocator keyAlloc; - CHIP_ERROR deleteErr = mStorage->SyncDeleteKeyValue(keyAlloc.FabricMetadata(fabricIndex)); + CHIP_ERROR deleteErr = mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::FabricMetadata(fabricIndex)); if (deleteErr != CHIP_NO_ERROR) { @@ -1059,9 +1054,8 @@ CHIP_ERROR FabricTable::Init(const FabricTable::InitParams & initParams) mLastKnownGoodTime.Init(mStorage); uint8_t buf[IndexInfoTLVMaxSize()]; - uint16_t size = sizeof(buf); - DefaultStorageKeyAllocator keyAlloc; - CHIP_ERROR err = mStorage->SyncGetKeyValue(keyAlloc.FabricIndexInfo(), buf, size); + uint16_t size = sizeof(buf); + CHIP_ERROR err = mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::FabricIndexInfo(), buf, size); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { // No fabrics yet. Nothing to be done here. @@ -1309,8 +1303,8 @@ CHIP_ERROR FabricTable::StoreFabricIndexInfo() const const auto indexInfoLength = writer.GetLengthWritten(); VerifyOrReturnError(CanCastTo(indexInfoLength), CHIP_ERROR_BUFFER_TOO_SMALL); - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncSetKeyValue(keyAlloc.FabricIndexInfo(), buf, static_cast(indexInfoLength))); + ReturnErrorOnFailure( + mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::FabricIndexInfo(), buf, static_cast(indexInfoLength))); return CHIP_NO_ERROR; } @@ -1415,7 +1409,6 @@ void FabricTable::ReleaseEphemeralKeypair(Crypto::P256Keypair * keypair) CHIP_ERROR FabricTable::StoreCommitMarker(const CommitMarker & commitMarker) { - DefaultStorageKeyAllocator keyAlloc; uint8_t tlvBuf[CommitMarkerContextTLVMaxSize()]; TLV::TLVWriter writer; writer.Init(tlvBuf); @@ -1429,15 +1422,15 @@ CHIP_ERROR FabricTable::StoreCommitMarker(const CommitMarker & commitMarker) const auto markerContextTLVLength = writer.GetLengthWritten(); VerifyOrReturnError(CanCastTo(markerContextTLVLength), CHIP_ERROR_BUFFER_TOO_SMALL); - return mStorage->SyncSetKeyValue(keyAlloc.FailSafeCommitMarkerKey(), tlvBuf, static_cast(markerContextTLVLength)); + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::FailSafeCommitMarkerKey(), tlvBuf, + static_cast(markerContextTLVLength)); } CHIP_ERROR FabricTable::GetCommitMarker(CommitMarker & outCommitMarker) { - DefaultStorageKeyAllocator keyAlloc; uint8_t tlvBuf[CommitMarkerContextTLVMaxSize()]; uint16_t tlvSize = sizeof(tlvBuf); - ReturnErrorOnFailure(mStorage->SyncGetKeyValue(keyAlloc.FailSafeCommitMarkerKey(), tlvBuf, tlvSize)); + ReturnErrorOnFailure(mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::FailSafeCommitMarkerKey(), tlvBuf, tlvSize)); // If buffer was too small, we won't reach here. TLV::ContiguousBufferTLVReader reader; @@ -1461,8 +1454,7 @@ CHIP_ERROR FabricTable::GetCommitMarker(CommitMarker & outCommitMarker) void FabricTable::ClearCommitMarker() { - DefaultStorageKeyAllocator keyAlloc; - mStorage->SyncDeleteKeyValue(keyAlloc.FailSafeCommitMarkerKey()); + mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::FailSafeCommitMarkerKey()); } bool FabricTable::HasOperationalKeyForFabric(FabricIndex fabricIndex) const diff --git a/src/credentials/GroupDataProviderImpl.cpp b/src/credentials/GroupDataProviderImpl.cpp index 5b015db48bf467..2da66cca048820 100644 --- a/src/credentials/GroupDataProviderImpl.cpp +++ b/src/credentials/GroupDataProviderImpl.cpp @@ -40,18 +40,17 @@ struct PersistentData { virtual ~PersistentData() = default; - virtual CHIP_ERROR UpdateKey(DefaultStorageKeyAllocator & key) = 0; - virtual CHIP_ERROR Serialize(TLV::TLVWriter & writer) const = 0; - virtual CHIP_ERROR Deserialize(TLV::TLVReader & reader) = 0; - virtual void Clear() = 0; + virtual CHIP_ERROR UpdateKey(StorageKeyName & key) = 0; + virtual CHIP_ERROR Serialize(TLV::TLVWriter & writer) const = 0; + virtual CHIP_ERROR Deserialize(TLV::TLVReader & reader) = 0; + virtual void Clear() = 0; virtual CHIP_ERROR Save(PersistentStorageDelegate * storage) { VerifyOrReturnError(nullptr != storage, CHIP_ERROR_INVALID_ARGUMENT); uint8_t buffer[kMaxSerializedSize] = { 0 }; - DefaultStorageKeyAllocator key; - // Update storage key + StorageKeyName key = StorageKeyName::Uninitialized(); ReturnErrorOnFailure(UpdateKey(key)); // Serialize the data @@ -60,7 +59,7 @@ struct PersistentData ReturnErrorOnFailure(Serialize(writer)); // Save serialized data - return storage->SyncSetKeyValue(key.KeyName(), buffer, static_cast(writer.GetLengthWritten())); + return storage->SyncSetKeyValue(key, buffer, static_cast(writer.GetLengthWritten())); } CHIP_ERROR Load(PersistentStorageDelegate * storage) @@ -68,17 +67,15 @@ struct PersistentData VerifyOrReturnError(nullptr != storage, CHIP_ERROR_INVALID_ARGUMENT); uint8_t buffer[kMaxSerializedSize] = { 0 }; - DefaultStorageKeyAllocator key; + StorageKeyName key = StorageKeyName::Uninitialized(); // Set data to defaults Clear(); - - // Update storage key ReturnErrorOnFailure(UpdateKey(key)); // Load the serialized data uint16_t size = static_cast(sizeof(buffer)); - CHIP_ERROR err = storage->SyncGetKeyValue(key.KeyName(), buffer, size); + CHIP_ERROR err = storage->SyncGetKeyValue(key, buffer, size); VerifyOrReturnError(CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND != err, CHIP_ERROR_NOT_FOUND); ReturnErrorOnFailure(err); @@ -92,11 +89,10 @@ struct PersistentData { VerifyOrReturnError(nullptr != storage, CHIP_ERROR_INVALID_ARGUMENT); - DefaultStorageKeyAllocator key; - // Update storage key + StorageKeyName key = StorageKeyName::Uninitialized(); ReturnErrorOnFailure(UpdateKey(key)); - // Delete stored data - return storage->SyncDeleteKeyValue(key.KeyName()); + + return storage->SyncDeleteKeyValue(key); } }; @@ -125,9 +121,9 @@ struct FabricList : public PersistentData FabricList() = default; FabricList(chip::FabricIndex first) : first_fabric(first), fabric_count(1) {} - CHIP_ERROR UpdateKey(DefaultStorageKeyAllocator & key) override + CHIP_ERROR UpdateKey(StorageKeyName & key) override { - key.GroupFabricList(); + key = DefaultStorageKeyAllocator::GroupFabricList(); return CHIP_NO_ERROR; } @@ -189,10 +185,10 @@ struct FabricData : public PersistentData FabricData() = default; FabricData(chip::FabricIndex fabric) : fabric_index(fabric) {} - CHIP_ERROR UpdateKey(DefaultStorageKeyAllocator & key) override + CHIP_ERROR UpdateKey(StorageKeyName & key) override { VerifyOrReturnError(kUndefinedFabricIndex != fabric_index, CHIP_ERROR_INVALID_FABRIC_INDEX); - key.FabricGroups(fabric_index); + key = DefaultStorageKeyAllocator::FabricGroups(fabric_index); return CHIP_NO_ERROR; } @@ -387,10 +383,10 @@ struct GroupData : public GroupDataProvider::GroupInfo, PersistentData fabric_index(fabric), keyset_id(id), policy(policy_id), keys_count(num_keys) {} - CHIP_ERROR UpdateKey(DefaultStorageKeyAllocator & key) override + CHIP_ERROR UpdateKey(StorageKeyName & key) override { VerifyOrReturnError(kUndefinedFabricIndex != fabric_index, CHIP_ERROR_INVALID_FABRIC_INDEX); VerifyOrReturnError(kInvalidKeysetId != keyset_id, CHIP_ERROR_INVALID_KEY_ID); - key.FabricKeyset(fabric_index, keyset_id); + key = DefaultStorageKeyAllocator::FabricKeyset(fabric_index, keyset_id); return CHIP_NO_ERROR; } diff --git a/src/credentials/LastKnownGoodTime.cpp b/src/credentials/LastKnownGoodTime.cpp index c840b3543b8ae5..c724fd5c680c9b 100644 --- a/src/credentials/LastKnownGoodTime.cpp +++ b/src/credentials/LastKnownGoodTime.cpp @@ -52,8 +52,7 @@ CHIP_ERROR LastKnownGoodTime::LoadLastKnownGoodChipEpochTime(System::Clock::Seco uint8_t buf[LastKnownGoodTimeTLVMaxSize()]; uint16_t size = sizeof(buf); uint32_t seconds; - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncGetKeyValue(keyAlloc.LastKnownGoodTimeKey(), buf, size)); + ReturnErrorOnFailure(mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::LastKnownGoodTimeKey(), buf, size)); TLV::ContiguousBufferTLVReader reader; reader.Init(buf, size); ReturnErrorOnFailure(reader.Next(TLV::kTLVType_Structure, TLV::AnonymousTag())); @@ -76,8 +75,8 @@ CHIP_ERROR LastKnownGoodTime::StoreLastKnownGoodChipEpochTime(System::Clock::Sec ReturnErrorOnFailure(writer.EndContainer(outerType)); const auto length = writer.GetLengthWritten(); VerifyOrReturnError(CanCastTo(length), CHIP_ERROR_BUFFER_TOO_SMALL); - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncSetKeyValue(keyAlloc.LastKnownGoodTimeKey(), buf, static_cast(length))); + ReturnErrorOnFailure( + mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::LastKnownGoodTimeKey(), buf, static_cast(length))); return CHIP_NO_ERROR; } diff --git a/src/credentials/PersistentStorageOpCertStore.cpp b/src/credentials/PersistentStorageOpCertStore.cpp index 081ab97ec92c31..0f58553c1f04d3 100644 --- a/src/credentials/PersistentStorageOpCertStore.cpp +++ b/src/credentials/PersistentStorageOpCertStore.cpp @@ -35,34 +35,31 @@ namespace { using CertChainElement = OperationalCertificateStore::CertChainElement; -const char * GetStorageKeyForCert(DefaultStorageKeyAllocator & keyAllocator, FabricIndex fabricIndex, CertChainElement element) +StorageKeyName GetStorageKeyForCert(FabricIndex fabricIndex, CertChainElement element) { - const char * storageKey = nullptr; - switch (element) { case CertChainElement::kNoc: - storageKey = keyAllocator.FabricNOC(fabricIndex); + return DefaultStorageKeyAllocator::FabricNOC(fabricIndex); break; case CertChainElement::kIcac: - storageKey = keyAllocator.FabricICAC(fabricIndex); + return DefaultStorageKeyAllocator::FabricICAC(fabricIndex); break; case CertChainElement::kRcac: - storageKey = keyAllocator.FabricRCAC(fabricIndex); + return DefaultStorageKeyAllocator::FabricRCAC(fabricIndex); break; default: break; } - return storageKey; + return StorageKeyName::Uninitialized(); } bool StorageHasCertificate(PersistentStorageDelegate * storage, FabricIndex fabricIndex, CertChainElement element) { - DefaultStorageKeyAllocator keyAllocator; - const char * storageKey = GetStorageKeyForCert(keyAllocator, fabricIndex, element); + StorageKeyName storageKey = GetStorageKeyForCert(fabricIndex, element); - if (storageKey == nullptr) + if (!storageKey) { return false; } @@ -81,8 +78,11 @@ bool StorageHasCertificate(PersistentStorageDelegate * storage, FabricIndex fabr CHIP_ERROR LoadCertFromStorage(PersistentStorageDelegate * storage, FabricIndex fabricIndex, CertChainElement element, MutableByteSpan & outCert) { - DefaultStorageKeyAllocator keyAllocator; - const char * storageKey = GetStorageKeyForCert(keyAllocator, fabricIndex, element); + StorageKeyName storageKey = GetStorageKeyForCert(fabricIndex, element); + if (!storageKey) + { + return CHIP_ERROR_INTERNAL; + } uint16_t keySize = static_cast(outCert.size()); CHIP_ERROR err = storage->SyncGetKeyValue(storageKey, outCert.data(), keySize); @@ -112,8 +112,11 @@ CHIP_ERROR LoadCertFromStorage(PersistentStorageDelegate * storage, FabricIndex CHIP_ERROR SaveCertToStorage(PersistentStorageDelegate * storage, FabricIndex fabricIndex, CertChainElement element, const ByteSpan & cert) { - DefaultStorageKeyAllocator keyAllocator; - const char * storageKey = GetStorageKeyForCert(keyAllocator, fabricIndex, element); + StorageKeyName storageKey = GetStorageKeyForCert(fabricIndex, element); + if (!storageKey) + { + return CHIP_ERROR_INTERNAL; + } // If provided an empty ICAC, we delete the ICAC key previously used. If not there, it's OK if ((element == CertChainElement::kIcac) && (cert.empty())) @@ -131,8 +134,11 @@ CHIP_ERROR SaveCertToStorage(PersistentStorageDelegate * storage, FabricIndex fa CHIP_ERROR DeleteCertFromStorage(PersistentStorageDelegate * storage, FabricIndex fabricIndex, CertChainElement element) { - DefaultStorageKeyAllocator keyAllocator; - const char * storageKey = GetStorageKeyForCert(keyAllocator, fabricIndex, element); + StorageKeyName storageKey = GetStorageKeyForCert(fabricIndex, element); + if (!storageKey) + { + return CHIP_ERROR_INTERNAL; + } return storage->SyncDeleteKeyValue(storageKey); } diff --git a/src/credentials/tests/TestPersistentStorageOpCertStore.cpp b/src/credentials/tests/TestPersistentStorageOpCertStore.cpp index fc807d92e17017..e2f99e2eaf93cd 100644 --- a/src/credentials/tests/TestPersistentStorageOpCertStore.cpp +++ b/src/credentials/tests/TestPersistentStorageOpCertStore.cpp @@ -51,7 +51,6 @@ void TestAddNocFlow(nlTestSuite * inSuite, void * inContext) { TestPersistentStorageDelegate storageDelegate; PersistentStorageOpCertStore opCertStore; - DefaultStorageKeyAllocator keyAllocator; // Failure before Init CHIP_ERROR err = opCertStore.AddNewTrustedRootCertForFabric(kFabricIndex1, kTestRcacSpan); @@ -66,7 +65,8 @@ void TestAddNocFlow(nlTestSuite * inSuite, void * inContext) // same fabric but succeed GetCertificate. const uint8_t kTestRcacBufExists[] = { 'r', 'c', 'a', 'c', ' ', 'e', 'x', 'i', 's', 't', 's' }; - err = storageDelegate.SyncSetKeyValue(keyAllocator.FabricRCAC(kFabricIndex1), kTestRcacBufExists, sizeof(kTestRcacBufExists)); + err = storageDelegate.SyncSetKeyValue(DefaultStorageKeyAllocator::FabricRCAC(kFabricIndex1), kTestRcacBufExists, + sizeof(kTestRcacBufExists)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 1); NL_TEST_ASSERT(inSuite, @@ -123,11 +123,13 @@ void TestAddNocFlow(nlTestSuite * inSuite, void * inContext) const uint8_t kTestIcacBufExists[] = { 'i', 'c', 'a', 'c', ' ', 'e', 'x', 'i', 's', 't', 's' }; const uint8_t kTestNocBufExists[] = { 'n', 'o', 'c', ' ', 'e', 'x', 'i', 's', 't', 's' }; - err = storageDelegate.SyncSetKeyValue(keyAllocator.FabricICAC(kFabricIndex2), kTestIcacBufExists, sizeof(kTestIcacBufExists)); + err = storageDelegate.SyncSetKeyValue(DefaultStorageKeyAllocator::FabricICAC(kFabricIndex2), kTestIcacBufExists, + sizeof(kTestIcacBufExists)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 1); - err = storageDelegate.SyncSetKeyValue(keyAllocator.FabricNOC(kFabricIndex2), kTestNocBufExists, sizeof(kTestNocBufExists)); + err = storageDelegate.SyncSetKeyValue(DefaultStorageKeyAllocator::FabricNOC(kFabricIndex2), kTestNocBufExists, + sizeof(kTestNocBufExists)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 2); @@ -140,8 +142,8 @@ void TestAddNocFlow(nlTestSuite * inSuite, void * inContext) NL_TEST_ASSERT(inSuite, !opCertStore.HasPendingNocChain()); NL_TEST_ASSERT(inSuite, opCertStore.HasPendingRootCert() == true); - storageDelegate.SyncDeleteKeyValue(keyAllocator.FabricICAC(kFabricIndex2)); - storageDelegate.SyncDeleteKeyValue(keyAllocator.FabricNOC(kFabricIndex2)); + storageDelegate.SyncDeleteKeyValue(DefaultStorageKeyAllocator::FabricICAC(kFabricIndex2)); + storageDelegate.SyncDeleteKeyValue(DefaultStorageKeyAllocator::FabricNOC(kFabricIndex2)); NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 0); // Trying to do AddNewOpCertsForFabric for same fabric as that with pending RCAC should succeed @@ -217,7 +219,6 @@ void TestUpdateNocFlow(nlTestSuite * inSuite, void * inContext) { TestPersistentStorageDelegate storageDelegate; PersistentStorageOpCertStore opCertStore; - DefaultStorageKeyAllocator keyAllocator; // Failure before Init CHIP_ERROR err = opCertStore.UpdateOpCertsForFabric(kFabricIndex1, kTestNocSpan, kTestIcacSpan); @@ -256,21 +257,22 @@ void TestUpdateNocFlow(nlTestSuite * inSuite, void * inContext) MutableByteSpan largeSpan{ largeBuf }; { - err = - storageDelegate.SyncSetKeyValue(keyAllocator.FabricRCAC(kFabricIndex1), kTestRcacBufExists, sizeof(kTestRcacBufExists)); + err = storageDelegate.SyncSetKeyValue(DefaultStorageKeyAllocator::FabricRCAC(kFabricIndex1), kTestRcacBufExists, + sizeof(kTestRcacBufExists)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 1); NL_TEST_ASSERT(inSuite, opCertStore.HasCertificateForFabric(kFabricIndex1, CertChainElement::kRcac) == true); //< From manual add - err = - storageDelegate.SyncSetKeyValue(keyAllocator.FabricICAC(kFabricIndex1), kTestIcacBufExists, sizeof(kTestIcacBufExists)); + err = storageDelegate.SyncSetKeyValue(DefaultStorageKeyAllocator::FabricICAC(kFabricIndex1), kTestIcacBufExists, + sizeof(kTestIcacBufExists)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 2); NL_TEST_ASSERT(inSuite, opCertStore.HasCertificateForFabric(kFabricIndex1, CertChainElement::kIcac) == true); //< From manual add - err = storageDelegate.SyncSetKeyValue(keyAllocator.FabricNOC(kFabricIndex1), kTestNocBufExists, sizeof(kTestNocBufExists)); + err = storageDelegate.SyncSetKeyValue(DefaultStorageKeyAllocator::FabricNOC(kFabricIndex1), kTestNocBufExists, + sizeof(kTestNocBufExists)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 3); NL_TEST_ASSERT(inSuite, @@ -345,8 +347,8 @@ void TestUpdateNocFlow(nlTestSuite * inSuite, void * inContext) NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); // Committing writes the new values (we even "background-remove" the old ICAC/NOC before commit) - storageDelegate.SyncDeleteKeyValue(keyAllocator.FabricICAC(kFabricIndex1)); - storageDelegate.SyncDeleteKeyValue(keyAllocator.FabricNOC(kFabricIndex1)); + storageDelegate.SyncDeleteKeyValue(DefaultStorageKeyAllocator::FabricICAC(kFabricIndex1)); + storageDelegate.SyncDeleteKeyValue(DefaultStorageKeyAllocator::FabricNOC(kFabricIndex1)); NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 1); //< Root remains err = opCertStore.CommitOpCertsForFabric(kFabricIndex1); diff --git a/src/crypto/PersistentStorageOperationalKeystore.cpp b/src/crypto/PersistentStorageOperationalKeystore.cpp index 94c19888dc93b0..e71f5168ab948a 100644 --- a/src/crypto/PersistentStorageOperationalKeystore.cpp +++ b/src/crypto/PersistentStorageOperationalKeystore.cpp @@ -79,9 +79,9 @@ CHIP_ERROR StoreOperationalKey(FabricIndex fabricIndex, PersistentStorageDelegat ReturnErrorOnFailure(writer.EndContainer(outerType)); const auto opKeyLength = writer.GetLengthWritten(); - DefaultStorageKeyAllocator keyAlloc; VerifyOrReturnError(CanCastTo(opKeyLength), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorOnFailure(storage->SyncSetKeyValue(keyAlloc.FabricOpKey(fabricIndex), buf, static_cast(opKeyLength))); + ReturnErrorOnFailure( + storage->SyncSetKeyValue(DefaultStorageKeyAllocator::FabricOpKey(fabricIndex), buf, static_cast(opKeyLength))); return CHIP_NO_ERROR; } @@ -111,9 +111,8 @@ CHIP_ERROR SignWithStoredOpKey(FabricIndex fabricIndex, PersistentStorageDelegat Crypto::CapacityBoundBuffer buf; // Load up the operational key structure from storage - uint16_t size = static_cast(buf.Capacity()); - DefaultStorageKeyAllocator keyAlloc; - CHIP_ERROR err = storage->SyncGetKeyValue(keyAlloc.FabricOpKey(fabricIndex), buf.Bytes(), size); + uint16_t size = static_cast(buf.Capacity()); + CHIP_ERROR err = storage->SyncGetKeyValue(DefaultStorageKeyAllocator::FabricOpKey(fabricIndex), buf.Bytes(), size); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { err = CHIP_ERROR_INVALID_FABRIC_INDEX; @@ -180,9 +179,8 @@ bool PersistentStorageOperationalKeystore::HasOpKeypairForFabric(FabricIndex fab // Use a CapacityBoundBuffer to get RAII secret data clearing on scope exit. Crypto::CapacityBoundBuffer buf; - DefaultStorageKeyAllocator keyAlloc; uint16_t keySize = static_cast(buf.Capacity()); - CHIP_ERROR err = mStorage->SyncGetKeyValue(keyAlloc.FabricOpKey(fabricIndex), buf.Bytes(), keySize); + CHIP_ERROR err = mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::FabricOpKey(fabricIndex), buf.Bytes(), keySize); return (err == CHIP_NO_ERROR); } @@ -262,8 +260,7 @@ CHIP_ERROR PersistentStorageOperationalKeystore::RemoveOpKeypairForFabric(Fabric RevertPendingKeypair(); } - DefaultStorageKeyAllocator keyAlloc; - CHIP_ERROR err = mStorage->SyncDeleteKeyValue(keyAlloc.FabricOpKey(fabricIndex)); + CHIP_ERROR err = mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::FabricOpKey(fabricIndex)); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { err = CHIP_ERROR_INVALID_FABRIC_INDEX; diff --git a/src/crypto/tests/TestPersistentStorageOpKeyStore.cpp b/src/crypto/tests/TestPersistentStorageOpKeyStore.cpp index b962626b59d4d1..73a987d486ef0e 100644 --- a/src/crypto/tests/TestPersistentStorageOpKeyStore.cpp +++ b/src/crypto/tests/TestPersistentStorageOpKeyStore.cpp @@ -167,8 +167,7 @@ void TestBasicLifeCycle(nlTestSuite * inSuite, void * inContext) NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == true); // Committing key resets pending state and adds storage - DefaultStorageKeyAllocator keyAllocator; - std::string opKeyStorageKey = keyAllocator.FabricOpKey(kFabricIndex); + std::string opKeyStorageKey = DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName(); err = opKeystore.CommitOpKeypairForFabric(kFabricIndex); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == false); diff --git a/src/lib/support/DefaultStorageKeyAllocator.h b/src/lib/support/DefaultStorageKeyAllocator.h index 920e834bfdcd36..4e19058852a3ac 100644 --- a/src/lib/support/DefaultStorageKeyAllocator.h +++ b/src/lib/support/DefaultStorageKeyAllocator.h @@ -18,16 +18,68 @@ #include #include -#include -#include -#include -#include +#include + #include -#include -#include namespace chip { +/** + * Represents a key used for addressing a specific storage element. + * + * May contain generic fixed keys (e.g. "g/fidx") or formatted fabric-specific + * keys ("f/%x/..." where %x is the fabric index). + */ +class StorageKeyName +{ +public: + StorageKeyName(const StorageKeyName & other) = default; + StorageKeyName & operator=(const StorageKeyName & other) = default; + + ~StorageKeyName() { memset(mKeyNameBuffer, 0, sizeof(mKeyNameBuffer)); } + + const char * KeyName() const { return mKeyNameBuffer; } + + bool IsInitialized() const { return mKeyNameBuffer[0] != 0; } + bool IsUninitialized() const { return mKeyNameBuffer[0] == 0; } + bool operator!() const { return IsUninitialized(); } + + operator const char *() const { return mKeyNameBuffer; } + + static StorageKeyName FromConst(const char * value) + { + StorageKeyName result; + Platform::CopyString(result.mKeyNameBuffer, value); + return result; + } + + static StorageKeyName ENFORCE_FORMAT(1, 2) Formatted(const char * format, ...) + { + StorageKeyName result; + + va_list args; + va_start(args, format); + vsnprintf(result.mKeyNameBuffer, sizeof(result.mKeyNameBuffer), format, args); + va_end(args); + + return result; + } + + // Explicit 0-filled key. MUST be initialized later + static StorageKeyName Uninitialized() + { + StorageKeyName result; + return result; + } + +private: + // May only be created by the underlying constructor methods + StorageKeyName() {} + + // Contains the storage for the key name because some strings may be formatted. + char mKeyNameBuffer[PersistentStorageDelegate::kKeyLengthMax + 1] = { 0 }; +}; + /** * This is the common key allocation policy for all classes using * PersistentStorageDelegate storage. @@ -40,99 +92,99 @@ namespace chip { */ class DefaultStorageKeyAllocator { -public: +private: DefaultStorageKeyAllocator() = default; - const char * KeyName() { return mKeyName; } +public: // Fabric Table - const char * FabricIndexInfo() { return SetConst("g/fidx"); } - const char * FabricNOC(FabricIndex fabric) { return Format("f/%x/n", fabric); } - const char * FabricICAC(FabricIndex fabric) { return Format("f/%x/i", fabric); } - const char * FabricRCAC(FabricIndex fabric) { return Format("f/%x/r", fabric); } - const char * FabricMetadata(FabricIndex fabric) { return Format("f/%x/m", fabric); } - const char * FabricOpKey(FabricIndex fabric) { return Format("f/%x/o", fabric); } + static StorageKeyName FabricIndexInfo() { return StorageKeyName::FromConst("g/fidx"); } + static StorageKeyName FabricNOC(FabricIndex fabric) { return StorageKeyName::Formatted("f/%x/n", fabric); } + static StorageKeyName FabricICAC(FabricIndex fabric) { return StorageKeyName::Formatted("f/%x/i", fabric); } + static StorageKeyName FabricRCAC(FabricIndex fabric) { return StorageKeyName::Formatted("f/%x/r", fabric); } + static StorageKeyName FabricMetadata(FabricIndex fabric) { return StorageKeyName::Formatted("f/%x/m", fabric); } + static StorageKeyName FabricOpKey(FabricIndex fabric) { return StorageKeyName::Formatted("f/%x/o", fabric); } // Fail-safe handling - const char * FailSafeCommitMarkerKey() { return SetConst("g/fs/c"); } - const char * FailSafeNetworkConfig() { return SetConst("g/fs/n"); } + static StorageKeyName FailSafeCommitMarkerKey() { return StorageKeyName::FromConst("g/fs/c"); } + static StorageKeyName FailSafeNetworkConfig() { return StorageKeyName::FromConst("g/fs/n"); } // LastKnownGoodTime - const char * LastKnownGoodTimeKey() { return SetConst("g/lkgt"); } + static StorageKeyName LastKnownGoodTimeKey() { return StorageKeyName::FromConst("g/lkgt"); } // Session resumption - const char * FabricSession(FabricIndex fabric, NodeId nodeId) + static StorageKeyName FabricSession(FabricIndex fabric, NodeId nodeId) + { + return StorageKeyName::Formatted("f/%x/s/%08" PRIX32 "%08" PRIX32, fabric, static_cast(nodeId >> 32), + static_cast(nodeId)); + } + + static StorageKeyName SessionResumptionIndex() { return StorageKeyName::FromConst("g/sri"); } + static StorageKeyName SessionResumption(const char * resumptionIdBase64) { - return Format("f/%x/s/%08" PRIX32 "%08" PRIX32, fabric, static_cast(nodeId >> 32), static_cast(nodeId)); + return StorageKeyName::Formatted("g/s/%s", resumptionIdBase64); } - const char * SessionResumptionIndex() { return SetConst("g/sri"); } - const char * SessionResumption(const char * resumptionIdBase64) { return Format("g/s/%s", resumptionIdBase64); } // Access Control - const char * AccessControlAclEntry(FabricIndex fabric, size_t index) + static StorageKeyName AccessControlAclEntry(FabricIndex fabric, size_t index) { - return Format("f/%x/ac/0/%x", fabric, static_cast(index)); + return StorageKeyName::Formatted("f/%x/ac/0/%x", fabric, static_cast(index)); } - const char * AccessControlExtensionEntry(FabricIndex fabric) { return Format("f/%x/ac/1", fabric); } + + static StorageKeyName AccessControlExtensionEntry(FabricIndex fabric) { return StorageKeyName::Formatted("f/%x/ac/1", fabric); } // Group Message Counters - const char * GroupDataCounter() { return SetConst("g/gdc"); } - const char * GroupControlCounter() { return SetConst("g/gcc"); } + static StorageKeyName GroupDataCounter() { return StorageKeyName::FromConst("g/gdc"); } + static StorageKeyName GroupControlCounter() { return StorageKeyName::FromConst("g/gcc"); } // Device Information Provider - const char * UserLabelLengthKey(EndpointId endpoint) { return Format("g/userlbl/%x", endpoint); } - const char * UserLabelIndexKey(EndpointId endpoint, uint32_t index) { return Format("g/userlbl/%x/%" PRIx32, endpoint, index); } + static StorageKeyName UserLabelLengthKey(EndpointId endpoint) { return StorageKeyName::Formatted("g/userlbl/%x", endpoint); } + static StorageKeyName UserLabelIndexKey(EndpointId endpoint, uint32_t index) + { + return StorageKeyName::Formatted("g/userlbl/%x/%" PRIx32, endpoint, index); + } // Group Data Provider // List of fabric indices that have endpoint-to-group associations defined. - const char * GroupFabricList() { return SetConst("g/gfl"); } - const char * FabricGroups(chip::FabricIndex fabric) { return Format("f/%x/g", fabric); } - const char * FabricGroup(chip::FabricIndex fabric, chip::GroupId group) { return Format("f/%x/g/%x", fabric, group); } - const char * FabricGroupKey(chip::FabricIndex fabric, uint16_t index) { return Format("f/%x/gk/%x", fabric, index); } - const char * FabricGroupEndpoint(chip::FabricIndex fabric, chip::GroupId group, chip::EndpointId endpoint) + static StorageKeyName GroupFabricList() { return StorageKeyName::FromConst("g/gfl"); } + static StorageKeyName FabricGroups(chip::FabricIndex fabric) { return StorageKeyName::Formatted("f/%x/g", fabric); } + static StorageKeyName FabricGroup(chip::FabricIndex fabric, chip::GroupId group) { - return Format("f/%x/g/%x/e/%x", fabric, group, endpoint); + return StorageKeyName::Formatted("f/%x/g/%x", fabric, group); + } + static StorageKeyName FabricGroupKey(chip::FabricIndex fabric, uint16_t index) + { + return StorageKeyName::Formatted("f/%x/gk/%x", fabric, index); + } + static StorageKeyName FabricGroupEndpoint(chip::FabricIndex fabric, chip::GroupId group, chip::EndpointId endpoint) + { + return StorageKeyName::Formatted("f/%x/g/%x/e/%x", fabric, group, endpoint); + } + static StorageKeyName FabricKeyset(chip::FabricIndex fabric, uint16_t keyset) + { + return StorageKeyName::Formatted("f/%x/k/%x", fabric, keyset); } - const char * FabricKeyset(chip::FabricIndex fabric, uint16_t keyset) { return Format("f/%x/k/%x", fabric, keyset); } - const char * AttributeValue(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId) + static StorageKeyName AttributeValue(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId) { // Needs at most 26 chars: 6 for "g/a///", 4 for the endpoint id, 8 each // for the cluster and attribute ids. - return Format("g/a/%x/%" PRIx32 "/%" PRIx32, endpointId, clusterId, attributeId); + return StorageKeyName::Formatted("g/a/%x/%" PRIx32 "/%" PRIx32, endpointId, clusterId, attributeId); } // TODO: Should store fabric-specific parts of the binding list under keys // starting with "f/%x/". - const char * BindingTable() { return SetConst("g/bt"); } - const char * BindingTableEntry(uint8_t index) { return Format("g/bt/%x", index); } + static StorageKeyName BindingTable() { return StorageKeyName::FromConst("g/bt"); } + static StorageKeyName BindingTableEntry(uint8_t index) { return StorageKeyName::Formatted("g/bt/%x", index); } - const char * OTADefaultProviders() { return SetConst("g/o/dp"); } - const char * OTACurrentProvider() { return SetConst("g/o/cp"); } - const char * OTAUpdateToken() { return SetConst("g/o/ut"); } - const char * OTACurrentUpdateState() { return SetConst("g/o/us"); } - const char * OTATargetVersion() { return SetConst("g/o/tv"); } + static StorageKeyName OTADefaultProviders() { return StorageKeyName::FromConst("g/o/dp"); } + static StorageKeyName OTACurrentProvider() { return StorageKeyName::FromConst("g/o/cp"); } + static StorageKeyName OTAUpdateToken() { return StorageKeyName::FromConst("g/o/ut"); } + static StorageKeyName OTACurrentUpdateState() { return StorageKeyName::FromConst("g/o/us"); } + static StorageKeyName OTATargetVersion() { return StorageKeyName::FromConst("g/o/tv"); } // Event number counter. - const char * IMEventNumber() { return SetConst("g/im/ec"); } - -protected: - // The ENFORCE_FORMAT args are "off by one" because this is a class method, - // with an implicit "this" as first arg. - const char * ENFORCE_FORMAT(2, 3) Format(const char * format, ...) - { - va_list args; - va_start(args, format); - vsnprintf(mKeyNameBuffer, sizeof(mKeyNameBuffer), format, args); - va_end(args); - return mKeyName = mKeyNameBuffer; - } - - const char * SetConst(const char * keyName) { return mKeyName = keyName; } - -private: - const char * mKeyName = nullptr; - char mKeyNameBuffer[PersistentStorageDelegate::kKeyLengthMax + 1] = { 0 }; + static StorageKeyName IMEventNumber() { return StorageKeyName::FromConst("g/im/ec"); } }; } // namespace chip diff --git a/src/lib/support/PersistedCounter.h b/src/lib/support/PersistedCounter.h index 9261da6ac9faff..bcdfc2032c75dd 100644 --- a/src/lib/support/PersistedCounter.h +++ b/src/lib/support/PersistedCounter.h @@ -60,11 +60,9 @@ template class PersistedCounter : public MonotonicallyIncreasingCounter { public: - PersistedCounter() {} + PersistedCounter() : mKey(StorageKeyName::Uninitialized()) {} ~PersistedCounter() override {} - typedef const char * (DefaultStorageKeyAllocator::*KeyType)(); - /** * @brief * Initialize a PersistedCounter object. @@ -78,7 +76,7 @@ class PersistedCounter : public MonotonicallyIncreasingCounter * CHIP_ERROR_INVALID_INTEGER_VALUE if aEpoch is 0. * CHIP_NO_ERROR otherwise */ - CHIP_ERROR Init(PersistentStorageDelegate * aStorage, KeyType aKey, T aEpoch) + CHIP_ERROR Init(PersistentStorageDelegate * aStorage, StorageKeyName aKey, T aEpoch) { VerifyOrReturnError(aStorage != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(aKey != nullptr, CHIP_ERROR_INVALID_ARGUMENT); @@ -122,7 +120,7 @@ class PersistedCounter : public MonotonicallyIncreasingCounter CHIP_ERROR Advance() override { VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); - VerifyOrReturnError(mKey != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mKey.IsInitialized(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(MonotonicallyIncreasingCounter::Advance()); @@ -165,9 +163,7 @@ class PersistedCounter : public MonotonicallyIncreasingCounter #endif T valueLE = Encoding::LittleEndian::HostSwap(aStartValue); - - DefaultStorageKeyAllocator keyAlloc; - return mStorage->SyncSetKeyValue((keyAlloc.*mKey)(), &valueLE, sizeof(valueLE)); + return mStorage->SyncSetKeyValue(mKey, &valueLE, sizeof(valueLE)); } /** @@ -180,11 +176,12 @@ class PersistedCounter : public MonotonicallyIncreasingCounter */ CHIP_ERROR ReadStartValue(T & aStartValue) { - DefaultStorageKeyAllocator keyAlloc; T valueLE = 0; uint16_t size = sizeof(valueLE); - CHIP_ERROR err = mStorage->SyncGetKeyValue((keyAlloc.*mKey)(), &valueLE, size); + VerifyOrReturnError(mKey.IsInitialized(), CHIP_ERROR_INCORRECT_STATE); + + CHIP_ERROR err = mStorage->SyncGetKeyValue(mKey, &valueLE, size); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { // No previously-stored value, no worries, the counter is initialized to zero. @@ -214,9 +211,9 @@ class PersistedCounter : public MonotonicallyIncreasingCounter } PersistentStorageDelegate * mStorage = nullptr; // start value is stored here - KeyType mKey = nullptr; - T mEpoch = 0; // epoch modulus value - T mNextEpoch = 0; // next epoch start + StorageKeyName mKey; + T mEpoch = 0; // epoch modulus value + T mNextEpoch = 0; // next epoch start }; } // namespace chip diff --git a/src/lib/support/tests/TestPersistedCounter.cpp b/src/lib/support/tests/TestPersistedCounter.cpp index ccbfbfd7629067..558a425a48df74 100644 --- a/src/lib/support/tests/TestPersistedCounter.cpp +++ b/src/lib/support/tests/TestPersistedCounter.cpp @@ -101,8 +101,7 @@ static void CheckOOB(nlTestSuite * inSuite, void * inContext) chip::PersistedCounter counter; - auto testKey = &chip::DefaultStorageKeyAllocator::IMEventNumber; - CHIP_ERROR err = counter.Init(sPersistentStore, testKey, 0x10000); + CHIP_ERROR err = counter.Init(sPersistentStore, chip::DefaultStorageKeyAllocator::IMEventNumber(), 0x10000); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); auto value = counter.GetValue(); @@ -120,9 +119,7 @@ static void CheckReboot(nlTestSuite * inSuite, void * inContext) // When initializing the first time out of the box, we should have // a count of 0. - auto testKey = &chip::DefaultStorageKeyAllocator::IMEventNumber; - - CHIP_ERROR err = counter.Init(sPersistentStore, testKey, 0x10000); + CHIP_ERROR err = counter.Init(sPersistentStore, chip::DefaultStorageKeyAllocator::IMEventNumber(), 0x10000); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); auto value = counter.GetValue(); @@ -130,7 +127,7 @@ static void CheckReboot(nlTestSuite * inSuite, void * inContext) // Now we "reboot", and we should get a count of 0x10000. - err = counter2.Init(sPersistentStore, testKey, 0x10000); + err = counter2.Init(sPersistentStore, chip::DefaultStorageKeyAllocator::IMEventNumber(), 0x10000); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); value = counter2.GetValue(); @@ -148,8 +145,7 @@ static void CheckWriteNextCounterStart(nlTestSuite * inSuite, void * inContext) // When initializing the first time out of the box, we should have // a count of 0. - auto testKey = &chip::DefaultStorageKeyAllocator::IMEventNumber; - CHIP_ERROR err = counter.Init(sPersistentStore, testKey, 0x10000); + CHIP_ERROR err = counter.Init(sPersistentStore, chip::DefaultStorageKeyAllocator::IMEventNumber(), 0x10000); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); auto value = counter.GetValue(); diff --git a/src/platform/ESP32/ESP32DeviceInfoProvider.cpp b/src/platform/ESP32/ESP32DeviceInfoProvider.cpp index ad848c13f8cbb1..4788bf65bdb0ba 100644 --- a/src/platform/ESP32/ESP32DeviceInfoProvider.cpp +++ b/src/platform/ESP32/ESP32DeviceInfoProvider.cpp @@ -96,22 +96,20 @@ bool ESP32DeviceInfoProvider::FixedLabelIteratorImpl::Next(FixedLabelType & outp CHIP_ERROR ESP32DeviceInfoProvider::SetUserLabelLength(EndpointId endpoint, size_t val) { VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); - DefaultStorageKeyAllocator keyAlloc; - return mStorage->SyncSetKeyValue(keyAlloc.UserLabelLengthKey(endpoint), &val, static_cast(sizeof(val))); + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::UserLabelLengthKey(endpoint), &val, + static_cast(sizeof(val))); } CHIP_ERROR ESP32DeviceInfoProvider::GetUserLabelLength(EndpointId endpoint, size_t & val) { VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); - DefaultStorageKeyAllocator keyAlloc; uint16_t len = static_cast(sizeof(val)); - return mStorage->SyncGetKeyValue(keyAlloc.UserLabelLengthKey(endpoint), &val, len); + return mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::UserLabelLengthKey(endpoint), &val, len); } CHIP_ERROR ESP32DeviceInfoProvider::SetUserLabelAt(EndpointId endpoint, size_t index, const UserLabelType & userLabel) { VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); - DefaultStorageKeyAllocator keyAlloc; uint8_t buf[UserLabelTLVMaxSize()]; TLV::TLVWriter writer; writer.Init(buf); @@ -122,15 +120,14 @@ CHIP_ERROR ESP32DeviceInfoProvider::SetUserLabelAt(EndpointId endpoint, size_t i ReturnErrorOnFailure(writer.PutString(kLabelValueTag, userLabel.value)); ReturnErrorOnFailure(writer.EndContainer(outerType)); - return mStorage->SyncSetKeyValue(keyAlloc.UserLabelIndexKey(endpoint, index), buf, + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::UserLabelIndexKey(endpoint, index), buf, static_cast(writer.GetLengthWritten())); } CHIP_ERROR ESP32DeviceInfoProvider::DeleteUserLabelAt(EndpointId endpoint, size_t index) { VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); - DefaultStorageKeyAllocator keyAlloc; - return mStorage->SyncDeleteKeyValue(keyAlloc.UserLabelIndexKey(endpoint, index)); + return mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::UserLabelIndexKey(endpoint, index)); } DeviceInfoProvider::UserLabelIterator * ESP32DeviceInfoProvider::IterateUserLabel(EndpointId endpoint) @@ -153,11 +150,11 @@ bool ESP32DeviceInfoProvider::UserLabelIteratorImpl::Next(UserLabelType & output VerifyOrReturnError(mProvider.mStorage != nullptr, false); VerifyOrReturnError(mIndex < mTotal, false); - DefaultStorageKeyAllocator keyAlloc; uint8_t buf[UserLabelTLVMaxSize()]; uint16_t len = static_cast(sizeof(buf)); - CHIP_ERROR err = mProvider.mStorage->SyncGetKeyValue(keyAlloc.UserLabelIndexKey(mEndpoint, mIndex), buf, len); + CHIP_ERROR err = + mProvider.mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::UserLabelIndexKey(mEndpoint, mIndex), buf, len); VerifyOrReturnError(err == CHIP_NO_ERROR, false); TLV::ContiguousBufferTLVReader reader; diff --git a/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp b/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp index c4ff7934d12a1d..4616099b3e7e98 100644 --- a/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp +++ b/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp @@ -67,19 +67,18 @@ CHIP_ERROR GenericThreadDriver::CommitConfiguration() // the backup, so that it cannot be restored. If no backup could be found, it means that the // configuration has not been modified since the fail-safe was armed, so return with no error. - DefaultStorageKeyAllocator key; - CHIP_ERROR error = KeyValueStoreMgr().Delete(key.FailSafeNetworkConfig()); + CHIP_ERROR error = KeyValueStoreMgr().Delete(DefaultStorageKeyAllocator::FailSafeNetworkConfig()); return error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND ? CHIP_NO_ERROR : error; } CHIP_ERROR GenericThreadDriver::RevertConfiguration() { - DefaultStorageKeyAllocator key; uint8_t datasetBytes[Thread::kSizeOperationalDataset]; size_t datasetLength; - CHIP_ERROR error = KeyValueStoreMgr().Get(key.FailSafeNetworkConfig(), datasetBytes, sizeof(datasetBytes), &datasetLength); + CHIP_ERROR error = KeyValueStoreMgr().Get(DefaultStorageKeyAllocator::FailSafeNetworkConfig(), datasetBytes, + sizeof(datasetBytes), &datasetLength); // If no backup could be found, it means that the network configuration has not been modified // since the fail-safe was armed, so return with no error. @@ -98,7 +97,7 @@ CHIP_ERROR GenericThreadDriver::RevertConfiguration() } // Always remove the backup, regardless if it can be successfully restored. - KeyValueStoreMgr().Delete(key.FailSafeNetworkConfig()); + KeyValueStoreMgr().Delete(DefaultStorageKeyAllocator::FailSafeNetworkConfig()); return error; } @@ -200,10 +199,8 @@ Status GenericThreadDriver::MatchesNetworkId(const Thread::OperationalDataset & CHIP_ERROR GenericThreadDriver::BackupConfiguration() { - DefaultStorageKeyAllocator key; - // If configuration is already backed up, return with no error - CHIP_ERROR err = KeyValueStoreMgr().Get(key.FailSafeNetworkConfig(), nullptr, 0); + CHIP_ERROR err = KeyValueStoreMgr().Get(DefaultStorageKeyAllocator::FailSafeNetworkConfig(), nullptr, 0); if (err == CHIP_NO_ERROR || err == CHIP_ERROR_BUFFER_TOO_SMALL) { @@ -212,7 +209,7 @@ CHIP_ERROR GenericThreadDriver::BackupConfiguration() ByteSpan dataset = mStagingNetwork.AsByteSpan(); - return KeyValueStoreMgr().Put(key.FailSafeNetworkConfig(), dataset.data(), dataset.size()); + return KeyValueStoreMgr().Put(DefaultStorageKeyAllocator::FailSafeNetworkConfig(), dataset.data(), dataset.size()); } size_t GenericThreadDriver::ThreadNetworkIterator::Count() diff --git a/src/platform/nxp/mw320/DeviceInfoProviderImpl.cpp b/src/platform/nxp/mw320/DeviceInfoProviderImpl.cpp index 92be9bd5842da3..0ed747f0f3e694 100644 --- a/src/platform/nxp/mw320/DeviceInfoProviderImpl.cpp +++ b/src/platform/nxp/mw320/DeviceInfoProviderImpl.cpp @@ -121,22 +121,19 @@ bool DeviceInfoProviderImpl::FixedLabelIteratorImpl::Next(FixedLabelType & outpu CHIP_ERROR DeviceInfoProviderImpl::SetUserLabelLength(EndpointId endpoint, size_t val) { - DefaultStorageKeyAllocator keyAlloc; - - return mStorage->SyncSetKeyValue(keyAlloc.UserLabelLengthKey(endpoint), &val, static_cast(sizeof(val))); + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::UserLabelLengthKey(endpoint), &val, + static_cast(sizeof(val))); } CHIP_ERROR DeviceInfoProviderImpl::GetUserLabelLength(EndpointId endpoint, size_t & val) { - DefaultStorageKeyAllocator keyAlloc; uint16_t len = static_cast(sizeof(val)); - return mStorage->SyncGetKeyValue(keyAlloc.UserLabelLengthKey(endpoint), &val, len); + return mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::UserLabelLengthKey(endpoint), &val, len); } CHIP_ERROR DeviceInfoProviderImpl::SetUserLabelAt(EndpointId endpoint, size_t index, const UserLabelType & userLabel) { - DefaultStorageKeyAllocator keyAlloc; uint8_t buf[UserLabelTLVMaxSize()]; TLV::TLVWriter writer; writer.Init(buf); @@ -147,15 +144,14 @@ CHIP_ERROR DeviceInfoProviderImpl::SetUserLabelAt(EndpointId endpoint, size_t in ReturnErrorOnFailure(writer.PutString(kLabelValueTag, userLabel.value)); ReturnErrorOnFailure(writer.EndContainer(outerType)); - return mStorage->SyncSetKeyValue(keyAlloc.UserLabelIndexKey(endpoint, index), buf, + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::UserLabelIndexKey(endpoint, index), buf, static_cast(writer.GetLengthWritten())); } CHIP_ERROR DeviceInfoProviderImpl::DeleteUserLabelAt(EndpointId endpoint, size_t index) { VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); - DefaultStorageKeyAllocator keyAlloc; - return mStorage->SyncDeleteKeyValue(keyAlloc.UserLabelIndexKey(endpoint, index)); + return mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::UserLabelIndexKey(endpoint, index)); } DeviceInfoProvider::UserLabelIterator * DeviceInfoProviderImpl::IterateUserLabel(EndpointId endpoint) @@ -179,11 +175,10 @@ bool DeviceInfoProviderImpl::UserLabelIteratorImpl::Next(UserLabelType & output) VerifyOrReturnError(mIndex < mTotal, false); - DefaultStorageKeyAllocator keyAlloc; uint8_t buf[UserLabelTLVMaxSize()]; uint16_t len = static_cast(sizeof(buf)); - err = mProvider.mStorage->SyncGetKeyValue(keyAlloc.UserLabelIndexKey(mEndpoint, mIndex), buf, len); + err = mProvider.mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::UserLabelIndexKey(mEndpoint, mIndex), buf, len); VerifyOrReturnError(err == CHIP_NO_ERROR, false); TLV::ContiguousBufferTLVReader reader; diff --git a/src/protocols/secure_channel/SimpleSessionResumptionStorage.cpp b/src/protocols/secure_channel/SimpleSessionResumptionStorage.cpp index d20a29db38e7de..d8100ae8497994 100644 --- a/src/protocols/secure_channel/SimpleSessionResumptionStorage.cpp +++ b/src/protocols/secure_channel/SimpleSessionResumptionStorage.cpp @@ -35,17 +35,17 @@ constexpr TLV::Tag SimpleSessionResumptionStorage::kResumptionIdTag; constexpr TLV::Tag SimpleSessionResumptionStorage::kSharedSecretTag; constexpr TLV::Tag SimpleSessionResumptionStorage::kCATTag; -const char * SimpleSessionResumptionStorage::StorageKey(DefaultStorageKeyAllocator & keyAlloc, const ScopedNodeId & node) +StorageKeyName SimpleSessionResumptionStorage::GetStorageKey(const ScopedNodeId & node) { - return keyAlloc.FabricSession(node.GetFabricIndex(), node.GetNodeId()); + return DefaultStorageKeyAllocator::FabricSession(node.GetFabricIndex(), node.GetNodeId()); } -const char * SimpleSessionResumptionStorage::StorageKey(DefaultStorageKeyAllocator & keyAlloc, ConstResumptionIdView resumptionId) +StorageKeyName SimpleSessionResumptionStorage::GetStorageKey(ConstResumptionIdView resumptionId) { char resumptionIdBase64[BASE64_ENCODED_LEN(resumptionId.size()) + 1]; auto len = Base64Encode(resumptionId.data(), resumptionId.size(), resumptionIdBase64); resumptionIdBase64[len] = '\0'; - return keyAlloc.SessionResumption(resumptionIdBase64); + return DefaultStorageKeyAllocator::SessionResumption(resumptionIdBase64); } CHIP_ERROR SimpleSessionResumptionStorage::SaveIndex(const SessionIndex & index) @@ -71,8 +71,8 @@ CHIP_ERROR SimpleSessionResumptionStorage::SaveIndex(const SessionIndex & index) const auto len = writer.GetLengthWritten(); VerifyOrReturnError(CanCastTo(len), CHIP_ERROR_BUFFER_TOO_SMALL); - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncSetKeyValue(keyAlloc.SessionResumptionIndex(), buf.data(), static_cast(len))); + ReturnErrorOnFailure( + mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::SessionResumptionIndex(), buf.data(), static_cast(len))); return CHIP_NO_ERROR; } @@ -82,8 +82,7 @@ CHIP_ERROR SimpleSessionResumptionStorage::LoadIndex(SessionIndex & index) std::array buf; uint16_t len = static_cast(buf.size()); - DefaultStorageKeyAllocator keyAlloc; - if (mStorage->SyncGetKeyValue(keyAlloc.SessionResumptionIndex(), buf.data(), len) != CHIP_NO_ERROR) + if (mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::SessionResumptionIndex(), buf.data(), len) != CHIP_NO_ERROR) { index.mSize = 0; return CHIP_NO_ERROR; @@ -150,8 +149,7 @@ CHIP_ERROR SimpleSessionResumptionStorage::SaveLink(ConstResumptionIdView resump const auto len = writer.GetLengthWritten(); VerifyOrDie(CanCastTo(len)); - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncSetKeyValue(StorageKey(keyAlloc, resumptionId), buf.data(), static_cast(len))); + ReturnErrorOnFailure(mStorage->SyncSetKeyValue(GetStorageKey(resumptionId), buf.data(), static_cast(len))); return CHIP_NO_ERROR; } @@ -160,8 +158,7 @@ CHIP_ERROR SimpleSessionResumptionStorage::LoadLink(ConstResumptionIdView resump std::array buf; uint16_t len = static_cast(buf.size()); - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncGetKeyValue(StorageKey(keyAlloc, resumptionId), buf.data(), len)); + ReturnErrorOnFailure(mStorage->SyncGetKeyValue(GetStorageKey(resumptionId), buf.data(), len)); TLV::ContiguousBufferTLVReader reader; reader.Init(buf.data(), len); @@ -188,8 +185,7 @@ CHIP_ERROR SimpleSessionResumptionStorage::LoadLink(ConstResumptionIdView resump CHIP_ERROR SimpleSessionResumptionStorage::DeleteLink(ConstResumptionIdView resumptionId) { - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncDeleteKeyValue(StorageKey(keyAlloc, resumptionId))); + ReturnErrorOnFailure(mStorage->SyncDeleteKeyValue(GetStorageKey(resumptionId))); return CHIP_NO_ERROR; } @@ -217,8 +213,7 @@ CHIP_ERROR SimpleSessionResumptionStorage::SaveState(const ScopedNodeId & node, const auto len = writer.GetLengthWritten(); VerifyOrDie(CanCastTo(len)); - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncSetKeyValue(StorageKey(keyAlloc, node), buf.data(), static_cast(len))); + ReturnErrorOnFailure(mStorage->SyncSetKeyValue(GetStorageKey(node), buf.data(), static_cast(len))); return CHIP_NO_ERROR; } @@ -228,8 +223,7 @@ CHIP_ERROR SimpleSessionResumptionStorage::LoadState(const ScopedNodeId & node, std::array buf; uint16_t len = static_cast(buf.size()); - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncGetKeyValue(StorageKey(keyAlloc, node), buf.data(), len)); + ReturnErrorOnFailure(mStorage->SyncGetKeyValue(GetStorageKey(node), buf.data(), len)); TLV::ContiguousBufferTLVReader reader; reader.Init(buf.data(), len); @@ -267,8 +261,7 @@ CHIP_ERROR SimpleSessionResumptionStorage::LoadState(const ScopedNodeId & node, CHIP_ERROR SimpleSessionResumptionStorage::DeleteState(const ScopedNodeId & node) { - DefaultStorageKeyAllocator keyAlloc; - ReturnErrorOnFailure(mStorage->SyncDeleteKeyValue(StorageKey(keyAlloc, node))); + ReturnErrorOnFailure(mStorage->SyncDeleteKeyValue(GetStorageKey(node))); return CHIP_NO_ERROR; } diff --git a/src/protocols/secure_channel/SimpleSessionResumptionStorage.h b/src/protocols/secure_channel/SimpleSessionResumptionStorage.h index 0fd2a9e3620354..ee2a98ee0b0c43 100644 --- a/src/protocols/secure_channel/SimpleSessionResumptionStorage.h +++ b/src/protocols/secure_channel/SimpleSessionResumptionStorage.h @@ -56,8 +56,8 @@ class SimpleSessionResumptionStorage : public DefaultSessionResumptionStorage Crypto::P256ECDHDerivedSecret & sharedSecret, CATValues & peerCATs) override; CHIP_ERROR DeleteState(const ScopedNodeId & node) override; - static const char * StorageKey(DefaultStorageKeyAllocator & keyAlloc, const ScopedNodeId & node); - static const char * StorageKey(DefaultStorageKeyAllocator & keyAlloc, ConstResumptionIdView resumptionId); + static StorageKeyName GetStorageKey(const ScopedNodeId & node); + static StorageKeyName GetStorageKey(ConstResumptionIdView resumptionId); private: static constexpr size_t MaxScopedNodeIdSize() { return TLV::EstimateStructOverhead(sizeof(NodeId), sizeof(FabricIndex)); } diff --git a/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp b/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp index ca3d673b53fd14..21664e1226787f 100644 --- a/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp +++ b/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp @@ -16,7 +16,6 @@ */ #include -#include #include #include #include @@ -257,17 +256,14 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) for (const auto & node : nodes) { uint16_t size = 0; - chip::DefaultStorageKeyAllocator keyAlloc; - auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::StorageKey(keyAlloc, node), nullptr, size); + auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(node), nullptr, size); NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } // Verify no link table persistent storage entries were leaked. for (auto & vector : vectors) { uint16_t size = 0; - chip::DefaultStorageKeyAllocator keyAlloc; - auto rv = - storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::StorageKey(keyAlloc, vector.resumptionId), nullptr, size); + auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(vector.resumptionId), nullptr, size); NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } } @@ -326,15 +322,13 @@ void TestDelete(nlTestSuite * inSuite, void * inContext) for (auto & vector : vectors) { uint16_t size = 0; - chip::DefaultStorageKeyAllocator keyAlloc; { - auto rv = - storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::StorageKey(keyAlloc, vector.node), nullptr, size); + auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(vector.node), nullptr, size); NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } { - auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::StorageKey(keyAlloc, vector.resumptionId), - nullptr, size); + auto rv = + storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(vector.resumptionId), nullptr, size); NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } } @@ -412,15 +406,13 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) for (auto & node : vector.nodes) { uint16_t size = 0; - chip::DefaultStorageKeyAllocator keyAlloc; { - auto rv = - storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::StorageKey(keyAlloc, node.node), nullptr, size); + auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(node.node), nullptr, size); NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } { - auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::StorageKey(keyAlloc, node.resumptionId), - nullptr, size); + auto rv = + storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(node.resumptionId), nullptr, size); NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } } diff --git a/src/transport/GroupPeerMessageCounter.cpp b/src/transport/GroupPeerMessageCounter.cpp index d44a20da84a91a..ec6608f65b0cd1 100644 --- a/src/transport/GroupPeerMessageCounter.cpp +++ b/src/transport/GroupPeerMessageCounter.cpp @@ -272,10 +272,9 @@ CHIP_ERROR GroupOutgoingCounters::Init(chip::PersistentStorageDelegate * storage // Spec 4.5.1.3 mStorage = storage_delegate; uint16_t size = static_cast(sizeof(uint32_t)); - DefaultStorageKeyAllocator key; uint32_t temp; CHIP_ERROR err; - err = mStorage->SyncGetKeyValue(key.GroupControlCounter(), &temp, size); + err = mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::GroupControlCounter(), &temp, size); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { // might be the first time we retrieve the value @@ -291,7 +290,7 @@ CHIP_ERROR GroupOutgoingCounters::Init(chip::PersistentStorageDelegate * storage mGroupControlCounter = temp; } - err = mStorage->SyncGetKeyValue(key.GroupDataCounter(), &temp, size); + err = mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::GroupDataCounter(), &temp, size); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { // might be the first time we retrieve the value @@ -309,11 +308,11 @@ CHIP_ERROR GroupOutgoingCounters::Init(chip::PersistentStorageDelegate * storage temp = mGroupControlCounter + GROUP_MSG_COUNTER_MIN_INCREMENT; size = static_cast(sizeof(temp)); - ReturnErrorOnFailure(mStorage->SyncSetKeyValue(key.GroupControlCounter(), &temp, size)); + ReturnErrorOnFailure(mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::GroupControlCounter(), &temp, size)); temp = mGroupDataCounter + GROUP_MSG_COUNTER_MIN_INCREMENT; - return mStorage->SyncSetKeyValue(key.GroupDataCounter(), &temp, size); + return mStorage->SyncSetKeyValue(DefaultStorageKeyAllocator::GroupDataCounter(), &temp, size); } uint32_t GroupOutgoingCounters::GetCounter(bool isControl) @@ -326,18 +325,19 @@ CHIP_ERROR GroupOutgoingCounters::IncrementCounter(bool isControl) uint32_t temp = 0; uint16_t size = static_cast(sizeof(uint32_t)); uint32_t value = 0; - DefaultStorageKeyAllocator key; + + StorageKeyName key = StorageKeyName::Uninitialized(); if (isControl) { mGroupControlCounter++; - key.GroupControlCounter(); + key = DefaultStorageKeyAllocator::GroupControlCounter(); value = mGroupControlCounter; } else { mGroupDataCounter++; - key.GroupDataCounter(); + key = DefaultStorageKeyAllocator::GroupDataCounter(); value = mGroupDataCounter; } @@ -346,11 +346,11 @@ CHIP_ERROR GroupOutgoingCounters::IncrementCounter(bool isControl) return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; } - ReturnErrorOnFailure(mStorage->SyncGetKeyValue(key.KeyName(), &temp, size)); + ReturnErrorOnFailure(mStorage->SyncGetKeyValue(key, &temp, size)); if (temp == value) { temp = value + GROUP_MSG_COUNTER_MIN_INCREMENT; - return mStorage->SyncSetKeyValue(key.KeyName(), &temp, sizeof(uint32_t)); + return mStorage->SyncSetKeyValue(key, &temp, sizeof(uint32_t)); } return CHIP_NO_ERROR; } diff --git a/src/transport/tests/TestGroupMessageCounter.cpp b/src/transport/tests/TestGroupMessageCounter.cpp index fb9b032f6c6edc..0641fa2a4c6f22 100644 --- a/src/transport/tests/TestGroupMessageCounter.cpp +++ b/src/transport/tests/TestGroupMessageCounter.cpp @@ -45,17 +45,17 @@ class TestGroupOutgoingCounters : public chip::Transport::GroupOutgoingCounters { uint32_t temp = 0; - DefaultStorageKeyAllocator key; + StorageKeyName key = StorageKeyName::Uninitialized(); if (isControl) { mGroupControlCounter = value; - key.GroupControlCounter(); + key = DefaultStorageKeyAllocator::GroupControlCounter(); } else { mGroupDataCounter = value; - key.GroupDataCounter(); + key = DefaultStorageKeyAllocator::GroupDataCounter(); } if (mStorage == nullptr) @@ -65,7 +65,7 @@ class TestGroupOutgoingCounters : public chip::Transport::GroupOutgoingCounters // Always Update storage for Test purposes temp = value + GROUP_MSG_COUNTER_MIN_INCREMENT; - mStorage->SyncSetKeyValue(key.KeyName(), &temp, sizeof(uint32_t)); + mStorage->SyncSetKeyValue(key, &temp, sizeof(uint32_t)); } };