Matter SDK Coverage Report
Current view: top level - controller - CHIPDeviceController.cpp (source / functions) Coverage Total Hit
Test: SHA:3f9cd168e84cd831b7699126f5296f5c5498690f Lines: 2.6 % 1869 48
Test Date: 2026-04-27 19:52:19 Functions: 3.0 % 197 6

            Line data    Source code
       1              : /*
       2              :  *
       3              :  *    Copyright (c) 2020-2024 Project CHIP Authors
       4              :  *    Copyright (c) 2013-2017 Nest Labs, Inc.
       5              :  *    All rights reserved.
       6              :  *
       7              :  *    Licensed under the Apache License, Version 2.0 (the "License");
       8              :  *    you may not use this file except in compliance with the License.
       9              :  *    You may obtain a copy of the License at
      10              :  *
      11              :  *        http://www.apache.org/licenses/LICENSE-2.0
      12              :  *
      13              :  *    Unless required by applicable law or agreed to in writing, software
      14              :  *    distributed under the License is distributed on an "AS IS" BASIS,
      15              :  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      16              :  *    See the License for the specific language governing permissions and
      17              :  *    limitations under the License.
      18              :  */
      19              : 
      20              : /**
      21              :  *    @file
      22              :  *      Implementation of CHIP Device Controller, a common class
      23              :  *      that implements discovery, pairing and provisioning of CHIP
      24              :  *      devices.
      25              :  *
      26              :  */
      27              : 
      28              : // module header, comes first
      29              : #include <controller/CHIPDeviceController.h>
      30              : 
      31              : #include <app-common/zap-generated/ids/Attributes.h>
      32              : #include <app-common/zap-generated/ids/Clusters.h>
      33              : 
      34              : #include <app/InteractionModelEngine.h>
      35              : #include <app/OperationalSessionSetup.h>
      36              : #include <app/server/Dnssd.h>
      37              : #include <controller/CurrentFabricRemover.h>
      38              : #include <controller/InvokeInteraction.h>
      39              : #include <controller/WriteInteraction.h>
      40              : #include <credentials/CHIPCert.h>
      41              : #include <credentials/DeviceAttestationCredsProvider.h>
      42              : #include <crypto/CHIPCryptoPAL.h>
      43              : #include <lib/address_resolve/AddressResolve.h>
      44              : #include <lib/core/CHIPCore.h>
      45              : #include <lib/core/CHIPEncoding.h>
      46              : #include <lib/core/CHIPSafeCasts.h>
      47              : #include <lib/core/ErrorStr.h>
      48              : #include <lib/core/NodeId.h>
      49              : #include <lib/support/Base64.h>
      50              : #include <lib/support/CHIPMem.h>
      51              : #include <lib/support/CodeUtils.h>
      52              : #include <lib/support/PersistentStorageMacros.h>
      53              : #include <lib/support/SafeInt.h>
      54              : #include <lib/support/ScopedMemoryBuffer.h>
      55              : #include <lib/support/ThreadOperationalDataset.h>
      56              : #include <lib/support/TimeUtils.h>
      57              : #include <lib/support/logging/CHIPLogging.h>
      58              : #include <messaging/ExchangeContext.h>
      59              : #include <platform/LockTracker.h>
      60              : #include <protocols/secure_channel/MessageCounterManager.h>
      61              : #include <setup_payload/QRCodeSetupPayloadParser.h>
      62              : #include <tracing/macros.h>
      63              : #include <tracing/metric_event.h>
      64              : 
      65              : #if CONFIG_NETWORK_LAYER_BLE
      66              : #include <ble/Ble.h>
      67              : #include <transport/raw/BLE.h>
      68              : #endif
      69              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
      70              : #include <transport/raw/WiFiPAF.h>
      71              : #endif
      72              : 
      73              : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
      74              : #include <platform/internal/NFCCommissioningManager.h>
      75              : #endif
      76              : 
      77              : #include <algorithm>
      78              : #include <array>
      79              : #include <errno.h>
      80              : #include <inttypes.h>
      81              : #include <limits>
      82              : #include <memory>
      83              : #include <stdint.h>
      84              : #include <stdlib.h>
      85              : #include <string>
      86              : #include <time.h>
      87              : 
      88              : using namespace chip::app;
      89              : using namespace chip::app::Clusters;
      90              : using namespace chip::Inet;
      91              : using namespace chip::System;
      92              : using namespace chip::Transport;
      93              : using namespace chip::Credentials;
      94              : using namespace chip::Crypto;
      95              : using namespace chip::Tracing;
      96              : 
      97              : namespace chip {
      98              : namespace Controller {
      99              : 
     100              : using namespace chip::Encoding;
     101              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
     102              : using namespace chip::Protocols::UserDirectedCommissioning;
     103              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
     104              : 
     105              : using chip::AddressResolve::Resolver;
     106              : using chip::AddressResolve::ResolveResult;
     107              : 
     108          275 : DeviceController::DeviceController()
     109              : {
     110           25 :     mState = State::NotInitialized;
     111           25 : }
     112              : 
     113            0 : CHIP_ERROR DeviceController::Init(ControllerInitParams params)
     114              : {
     115            0 :     assertChipStackLockedByCurrentThread();
     116              : 
     117            0 :     VerifyOrReturnError(mState == State::NotInitialized, CHIP_ERROR_INCORRECT_STATE);
     118            0 :     VerifyOrReturnError(params.systemState != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     119              : 
     120            0 :     VerifyOrReturnError(params.systemState->SystemLayer() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     121            0 :     VerifyOrReturnError(params.systemState->UDPEndPointManager() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     122              : 
     123              : #if CONFIG_NETWORK_LAYER_BLE
     124            0 :     VerifyOrReturnError(params.systemState->BleLayer() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     125              : #endif
     126              : 
     127            0 :     VerifyOrReturnError(params.systemState->TransportMgr() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     128              : 
     129            0 :     ReturnErrorOnFailure(mDNSResolver.Init(params.systemState->UDPEndPointManager()));
     130            0 :     mDNSResolver.SetDiscoveryDelegate(this);
     131            0 :     RegisterDeviceDiscoveryDelegate(params.deviceDiscoveryDelegate);
     132              : 
     133            0 :     mVendorId = params.controllerVendorId;
     134            0 :     if (params.operationalKeypair != nullptr || !params.controllerNOC.empty() || !params.controllerRCAC.empty())
     135              :     {
     136            0 :         ReturnErrorOnFailure(InitControllerNOCChain(params));
     137              :     }
     138            0 :     else if (params.fabricIndex.HasValue())
     139              :     {
     140            0 :         VerifyOrReturnError(params.systemState->Fabrics()->FabricCount() > 0, CHIP_ERROR_INVALID_ARGUMENT);
     141            0 :         if (params.systemState->Fabrics()->FindFabricWithIndex(params.fabricIndex.Value()) != nullptr)
     142              :         {
     143            0 :             mFabricIndex = params.fabricIndex.Value();
     144              :         }
     145              :         else
     146              :         {
     147            0 :             ChipLogError(Controller, "There is no fabric corresponding to the given fabricIndex");
     148            0 :             return CHIP_ERROR_INVALID_ARGUMENT;
     149              :         }
     150              :     }
     151              : 
     152            0 :     mSystemState = params.systemState->Retain();
     153            0 :     mState       = State::Initialized;
     154              : 
     155            0 :     mRemoveFromFabricTableOnShutdown = params.removeFromFabricTableOnShutdown;
     156            0 :     mDeleteFromFabricTableOnShutdown = params.deleteFromFabricTableOnShutdown;
     157              : 
     158            0 :     if (GetFabricIndex() != kUndefinedFabricIndex)
     159              :     {
     160            0 :         ChipLogProgress(Controller,
     161              :                         "Joined the fabric at index %d. Fabric ID is 0x" ChipLogFormatX64
     162              :                         " (Compressed Fabric ID: " ChipLogFormatX64 ")",
     163              :                         GetFabricIndex(), ChipLogValueX64(GetFabricId()), ChipLogValueX64(GetCompressedFabricId()));
     164              :     }
     165              : 
     166            0 :     return CHIP_NO_ERROR;
     167              : }
     168              : 
     169            0 : CHIP_ERROR DeviceController::InitControllerNOCChain(const ControllerInitParams & params)
     170              : {
     171            0 :     FabricInfo newFabric;
     172            0 :     constexpr uint32_t chipCertAllocatedLen = kMaxCHIPCertLength;
     173            0 :     chip::Platform::ScopedMemoryBuffer<uint8_t> rcacBuf;
     174            0 :     chip::Platform::ScopedMemoryBuffer<uint8_t> icacBuf;
     175            0 :     chip::Platform::ScopedMemoryBuffer<uint8_t> nocBuf;
     176            0 :     Credentials::P256PublicKeySpan rootPublicKeySpan;
     177              :     FabricId fabricId;
     178              :     NodeId nodeId;
     179            0 :     bool hasExternallyOwnedKeypair                   = false;
     180            0 :     Crypto::P256Keypair * externalOperationalKeypair = nullptr;
     181            0 :     VendorId newFabricVendorId                       = params.controllerVendorId;
     182              : 
     183              :     // There are three possibilities here in terms of what happens with our
     184              :     // operational key:
     185              :     // 1) We have an externally owned operational keypair.
     186              :     // 2) We have an operational keypair that the fabric table should clone via
     187              :     //    serialize/deserialize.
     188              :     // 3) We have no keypair at all, and the fabric table has been initialized
     189              :     //    with a key store.
     190            0 :     if (params.operationalKeypair != nullptr)
     191              :     {
     192            0 :         hasExternallyOwnedKeypair  = params.hasExternallyOwnedOperationalKeypair;
     193            0 :         externalOperationalKeypair = params.operationalKeypair;
     194              :     }
     195              : 
     196            0 :     VerifyOrReturnError(rcacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
     197            0 :     VerifyOrReturnError(icacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
     198            0 :     VerifyOrReturnError(nocBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
     199              : 
     200            0 :     MutableByteSpan rcacSpan(rcacBuf.Get(), chipCertAllocatedLen);
     201              : 
     202            0 :     ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerRCAC, rcacSpan));
     203            0 :     ReturnErrorOnFailure(Credentials::ExtractPublicKeyFromChipCert(rcacSpan, rootPublicKeySpan));
     204            0 :     Crypto::P256PublicKey rootPublicKey{ rootPublicKeySpan };
     205              : 
     206            0 :     MutableByteSpan icacSpan;
     207            0 :     if (params.controllerICAC.empty())
     208              :     {
     209            0 :         ChipLogProgress(Controller, "Intermediate CA is not needed");
     210              :     }
     211              :     else
     212              :     {
     213            0 :         icacSpan = MutableByteSpan(icacBuf.Get(), chipCertAllocatedLen);
     214            0 :         ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerICAC, icacSpan));
     215              :     }
     216              : 
     217            0 :     MutableByteSpan nocSpan = MutableByteSpan(nocBuf.Get(), chipCertAllocatedLen);
     218              : 
     219            0 :     ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerNOC, nocSpan));
     220            0 :     ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(nocSpan, &nodeId, &fabricId));
     221              : 
     222            0 :     auto * fabricTable            = params.systemState->Fabrics();
     223            0 :     const FabricInfo * fabricInfo = nullptr;
     224              : 
     225              :     //
     226              :     // When multiple controllers are permitted on the same fabric, we need to find fabrics with
     227              :     // nodeId as an extra discriminant since we can have multiple FabricInfo objects that all
     228              :     // collide on the same fabric. Not doing so may result in a match with an existing FabricInfo
     229              :     // instance that matches the fabric in the provided NOC but is associated with a different NodeId
     230              :     // that is already in use by another active controller instance. That will effectively cause it
     231              :     // to change its identity inadvertently, which is not acceptable.
     232              :     //
     233              :     // TODO: Figure out how to clean up unreclaimed FabricInfos restored from persistent
     234              :     //       storage that are not in use by active DeviceController instances. Also, figure out
     235              :     //       how to reclaim FabricInfo slots when a DeviceController instance is deleted.
     236              :     //
     237            0 :     if (params.permitMultiControllerFabrics)
     238              :     {
     239            0 :         fabricInfo = fabricTable->FindIdentity(rootPublicKey, fabricId, nodeId);
     240              :     }
     241              :     else
     242              :     {
     243            0 :         fabricInfo = fabricTable->FindFabric(rootPublicKey, fabricId);
     244              :     }
     245              : 
     246            0 :     bool fabricFoundInTable = (fabricInfo != nullptr);
     247              : 
     248            0 :     FabricIndex fabricIndex = fabricFoundInTable ? fabricInfo->GetFabricIndex() : kUndefinedFabricIndex;
     249              : 
     250            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
     251              : 
     252            0 :     auto advertiseOperational =
     253            0 :         params.enableServerInteractions ? FabricTable::AdvertiseIdentity::Yes : FabricTable::AdvertiseIdentity::No;
     254              : 
     255              :     //
     256              :     // We permit colliding fabrics when multiple controllers are present on the same logical fabric
     257              :     // since each controller is associated with a unique FabricInfo 'identity' object and consequently,
     258              :     // a unique FabricIndex.
     259              :     //
     260              :     // This sets a flag that will be cleared automatically when the fabric is committed/reverted later
     261              :     // in this function.
     262              :     //
     263            0 :     if (params.permitMultiControllerFabrics)
     264              :     {
     265            0 :         fabricTable->PermitCollidingFabrics();
     266              :     }
     267              : 
     268              :     // We have 4 cases to handle legacy usage of direct operational key injection
     269            0 :     if (externalOperationalKeypair)
     270              :     {
     271              :         // Cases 1 and 2: Injected operational keys
     272              : 
     273              :         // CASE 1: Fabric update with injected key
     274            0 :         if (fabricFoundInTable)
     275              :         {
     276            0 :             err = fabricTable->UpdatePendingFabricWithProvidedOpKey(fabricIndex, nocSpan, icacSpan, externalOperationalKeypair,
     277              :                                                                     hasExternallyOwnedKeypair, advertiseOperational);
     278              :         }
     279              :         else
     280              :         // CASE 2: New fabric with injected key
     281              :         {
     282            0 :             err = fabricTable->AddNewPendingTrustedRootCert(rcacSpan);
     283            0 :             if (err == CHIP_NO_ERROR)
     284              :             {
     285            0 :                 err = fabricTable->AddNewPendingFabricWithProvidedOpKey(nocSpan, icacSpan, newFabricVendorId,
     286              :                                                                         externalOperationalKeypair, hasExternallyOwnedKeypair,
     287              :                                                                         &fabricIndex, advertiseOperational);
     288              :             }
     289              :         }
     290              :     }
     291              :     else
     292              :     {
     293              :         // Cases 3 and 4: OperationalKeystore has the keys
     294              : 
     295              :         // CASE 3: Fabric update with operational keystore
     296            0 :         if (fabricFoundInTable)
     297              :         {
     298            0 :             VerifyOrReturnError(fabricTable->HasOperationalKeyForFabric(fabricIndex), CHIP_ERROR_KEY_NOT_FOUND);
     299              : 
     300            0 :             err = fabricTable->UpdatePendingFabricWithOperationalKeystore(fabricIndex, nocSpan, icacSpan, advertiseOperational);
     301              :         }
     302              :         else
     303              :         // CASE 4: New fabric with operational keystore
     304              :         {
     305            0 :             err = fabricTable->AddNewPendingTrustedRootCert(rcacSpan);
     306            0 :             if (err == CHIP_NO_ERROR)
     307              :             {
     308            0 :                 err = fabricTable->AddNewPendingFabricWithOperationalKeystore(nocSpan, icacSpan, newFabricVendorId, &fabricIndex,
     309              :                                                                               advertiseOperational);
     310              :             }
     311              : 
     312            0 :             if (err == CHIP_NO_ERROR)
     313              :             {
     314              :                 // Now that we know our planned fabric index, verify that the
     315              :                 // keystore has a key for it.
     316            0 :                 if (!fabricTable->HasOperationalKeyForFabric(fabricIndex))
     317              :                 {
     318            0 :                     err = CHIP_ERROR_KEY_NOT_FOUND;
     319              :                 }
     320              :             }
     321              :         }
     322              :     }
     323              : 
     324              :     // Commit after setup, error-out on failure.
     325            0 :     if (err == CHIP_NO_ERROR)
     326              :     {
     327              :         // No need to revert on error: CommitPendingFabricData reverts internally on *any* error.
     328            0 :         err = fabricTable->CommitPendingFabricData();
     329              :     }
     330              :     else
     331              :     {
     332            0 :         fabricTable->RevertPendingFabricData();
     333              :     }
     334              : 
     335            0 :     ReturnErrorOnFailure(err);
     336            0 :     VerifyOrReturnError(fabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INTERNAL);
     337              : 
     338            0 :     mFabricIndex       = fabricIndex;
     339            0 :     mAdvertiseIdentity = advertiseOperational;
     340            0 :     return CHIP_NO_ERROR;
     341            0 : }
     342              : 
     343            0 : CHIP_ERROR DeviceController::UpdateControllerNOCChain(const ByteSpan & noc, const ByteSpan & icac,
     344              :                                                       Crypto::P256Keypair * operationalKeypair,
     345              :                                                       bool operationalKeypairExternalOwned)
     346              : {
     347            0 :     VerifyOrReturnError(mFabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INTERNAL);
     348            0 :     VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INTERNAL);
     349            0 :     FabricTable * fabricTable = mSystemState->Fabrics();
     350            0 :     CHIP_ERROR err            = CHIP_NO_ERROR;
     351              :     FabricId fabricId;
     352              :     NodeId nodeId;
     353            0 :     CATValues oldCats;
     354            0 :     CATValues newCats;
     355            0 :     ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(noc, &nodeId, &fabricId));
     356            0 :     ReturnErrorOnFailure(fabricTable->FetchCATs(mFabricIndex, oldCats));
     357            0 :     ReturnErrorOnFailure(ExtractCATsFromOpCert(noc, newCats));
     358              : 
     359            0 :     bool needCloseSession = true;
     360            0 :     if (GetFabricInfo()->GetNodeId() == nodeId && oldCats == newCats)
     361              :     {
     362            0 :         needCloseSession = false;
     363              :     }
     364              : 
     365            0 :     if (operationalKeypair != nullptr)
     366              :     {
     367            0 :         err = fabricTable->UpdatePendingFabricWithProvidedOpKey(mFabricIndex, noc, icac, operationalKeypair,
     368              :                                                                 operationalKeypairExternalOwned, mAdvertiseIdentity);
     369              :     }
     370              :     else
     371              :     {
     372            0 :         VerifyOrReturnError(fabricTable->HasOperationalKeyForFabric(mFabricIndex), CHIP_ERROR_KEY_NOT_FOUND);
     373            0 :         err = fabricTable->UpdatePendingFabricWithOperationalKeystore(mFabricIndex, noc, icac, mAdvertiseIdentity);
     374              :     }
     375              : 
     376            0 :     if (err == CHIP_NO_ERROR)
     377              :     {
     378            0 :         err = fabricTable->CommitPendingFabricData();
     379              :     }
     380              :     else
     381              :     {
     382            0 :         fabricTable->RevertPendingFabricData();
     383              :     }
     384              : 
     385            0 :     ReturnErrorOnFailure(err);
     386            0 :     if (needCloseSession)
     387              :     {
     388              :         // If the node id or CATs have changed, our existing CASE sessions are no longer valid,
     389              :         // because the other side will think anything coming over those sessions comes from our
     390              :         // old node ID, and the new CATs might not satisfy the ACL requirements of the other side.
     391            0 :         mSystemState->SessionMgr()->ExpireAllSessionsForFabric(mFabricIndex);
     392              :     }
     393            0 :     ChipLogProgress(Controller, "Controller NOC chain has updated");
     394            0 :     return CHIP_NO_ERROR;
     395              : }
     396              : 
     397            0 : void DeviceController::Shutdown()
     398              : {
     399            0 :     assertChipStackLockedByCurrentThread();
     400              : 
     401            0 :     VerifyOrReturn(mState != State::NotInitialized);
     402              : 
     403              :     // If our state is initialialized it means mSystemState is valid,
     404              :     // and we can use it below before we release our reference to it.
     405            0 :     ChipLogDetail(Controller, "Shutting down the controller");
     406            0 :     mState = State::NotInitialized;
     407              : 
     408            0 :     if (mFabricIndex != kUndefinedFabricIndex)
     409              :     {
     410              :         // Shut down any subscription clients for this fabric.
     411            0 :         app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(mFabricIndex);
     412              : 
     413              :         // Shut down any ongoing CASE session activity we have.  We're going to
     414              :         // assume that all sessions for our fabric belong to us here.
     415            0 :         mSystemState->CASESessionMgr()->ReleaseSessionsForFabric(mFabricIndex);
     416              : 
     417              :         // Shut down any bdx transfers we're acting as the server for.
     418            0 :         mSystemState->BDXTransferServer()->AbortTransfersForFabric(mFabricIndex);
     419              : 
     420              :         // TODO: The CASE session manager does not shut down existing CASE
     421              :         // sessions.  It just shuts down any ongoing CASE session establishment
     422              :         // we're in the middle of as initiator.  Maybe it should shut down
     423              :         // existing sessions too?
     424            0 :         mSystemState->SessionMgr()->ExpireAllSessionsForFabric(mFabricIndex);
     425              : 
     426            0 :         if (mDeleteFromFabricTableOnShutdown)
     427              :         {
     428            0 :             TEMPORARY_RETURN_IGNORED mSystemState->Fabrics()->Delete(mFabricIndex);
     429              :         }
     430            0 :         else if (mRemoveFromFabricTableOnShutdown)
     431              :         {
     432            0 :             mSystemState->Fabrics()->Forget(mFabricIndex);
     433              :         }
     434              :     }
     435              : 
     436            0 :     mSystemState->Release();
     437            0 :     mSystemState = nullptr;
     438              : 
     439            0 :     mDNSResolver.Shutdown();
     440            0 :     mDeviceDiscoveryDelegate = nullptr;
     441              : }
     442              : 
     443            0 : CHIP_ERROR DeviceController::GetPeerAddressAndPort(NodeId peerId, Inet::IPAddress & addr, uint16_t & port)
     444              : {
     445            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
     446            0 :     Transport::PeerAddress peerAddr;
     447            0 :     ReturnErrorOnFailure(mSystemState->CASESessionMgr()->GetPeerAddress(GetPeerScopedId(peerId), peerAddr));
     448            0 :     addr = peerAddr.GetIPAddress();
     449            0 :     port = peerAddr.GetPort();
     450            0 :     return CHIP_NO_ERROR;
     451              : }
     452              : 
     453            0 : CHIP_ERROR DeviceController::GetPeerAddress(NodeId nodeId, Transport::PeerAddress & addr)
     454              : {
     455            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
     456            0 :     ReturnErrorOnFailure(mSystemState->CASESessionMgr()->GetPeerAddress(GetPeerScopedId(nodeId), addr));
     457              : 
     458            0 :     return CHIP_NO_ERROR;
     459              : }
     460              : 
     461            0 : CHIP_ERROR DeviceController::ComputePASEVerifier(uint32_t iterations, uint32_t setupPincode, const ByteSpan & salt,
     462              :                                                  Spake2pVerifier & outVerifier)
     463              : {
     464            0 :     ReturnErrorOnFailure(PASESession::GeneratePASEVerifier(outVerifier, iterations, salt, /* useRandomPIN= */ false, setupPincode));
     465              : 
     466            0 :     return CHIP_NO_ERROR;
     467              : }
     468              : 
     469            0 : ControllerDeviceInitParams DeviceController::GetControllerDeviceInitParams()
     470              : {
     471              :     return ControllerDeviceInitParams{
     472            0 :         .sessionManager = mSystemState->SessionMgr(),
     473            0 :         .exchangeMgr    = mSystemState->ExchangeMgr(),
     474            0 :     };
     475              : }
     476              : 
     477           13 : DeviceCommissioner::DeviceCommissioner() :
     478           13 :     mOnDeviceConnectedCallback(OnDeviceConnectedFn, this), mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureFn, this),
     479              : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
     480           13 :     mOnDeviceConnectionRetryCallback(OnDeviceConnectionRetryFn, this),
     481              : #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
     482           13 :     mDeviceAttestationInformationVerificationCallback(OnDeviceAttestationInformationVerification, this),
     483           26 :     mDeviceNOCChainCallback(OnDeviceNOCChainGeneration, this), mSetUpCodePairer(this)
     484              : {
     485              : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
     486              :     (void) mPeerAdminJFAdminClusterEndpointId;
     487              : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
     488           13 : }
     489              : 
     490            0 : CHIP_ERROR DeviceCommissioner::Init(CommissionerInitParams params)
     491              : {
     492            0 :     VerifyOrReturnError(params.operationalCredentialsDelegate != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     493            0 :     mOperationalCredentialsDelegate = params.operationalCredentialsDelegate;
     494            0 :     ReturnErrorOnFailure(DeviceController::Init(params));
     495              : 
     496            0 :     mPairingDelegate = params.pairingDelegate;
     497              : 
     498              :     // Configure device attestation validation
     499            0 :     mDeviceAttestationVerifier = params.deviceAttestationVerifier;
     500            0 :     if (mDeviceAttestationVerifier == nullptr)
     501              :     {
     502            0 :         mDeviceAttestationVerifier = Credentials::GetDeviceAttestationVerifier();
     503            0 :         if (mDeviceAttestationVerifier == nullptr)
     504              :         {
     505            0 :             ChipLogError(Controller,
     506              :                          "Missing DeviceAttestationVerifier configuration at DeviceCommissioner init and none set with "
     507              :                          "Credentials::SetDeviceAttestationVerifier()!");
     508            0 :             return CHIP_ERROR_INVALID_ARGUMENT;
     509              :         }
     510              : 
     511              :         // We fell back on a default from singleton accessor.
     512            0 :         ChipLogProgress(Controller,
     513              :                         "*** Missing DeviceAttestationVerifier configuration at DeviceCommissioner init: using global default, "
     514              :                         "consider passing one in CommissionerInitParams.");
     515              :     }
     516              : 
     517            0 :     if (params.defaultCommissioner != nullptr)
     518              :     {
     519            0 :         mDefaultCommissioner = params.defaultCommissioner;
     520              :     }
     521              :     // Otherwise leave it pointing to mAutoCommissioner.
     522              : 
     523              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
     524              :     mUdcTransportMgr = chip::Platform::New<UdcTransportMgr>();
     525              :     ReturnErrorOnFailure(mUdcTransportMgr->Init(Transport::UdpListenParameters(mSystemState->UDPEndPointManager())
     526              :                                                     .SetAddressType(Inet::IPAddressType::kIPv6)
     527              :                                                     .SetListenPort(static_cast<uint16_t>(mUdcListenPort))
     528              : #if INET_CONFIG_ENABLE_IPV4
     529              :                                                     ,
     530              :                                                 Transport::UdpListenParameters(mSystemState->UDPEndPointManager())
     531              :                                                     .SetAddressType(Inet::IPAddressType::kIPv4)
     532              :                                                     .SetListenPort(static_cast<uint16_t>(mUdcListenPort))
     533              : #endif // INET_CONFIG_ENABLE_IPV4
     534              :                                                     ));
     535              : 
     536              :     mUdcServer = chip::Platform::New<UserDirectedCommissioningServer>();
     537              :     mUdcTransportMgr->SetSessionManager(mUdcServer);
     538              :     mUdcServer->SetTransportManager(mUdcTransportMgr);
     539              : 
     540              :     mUdcServer->SetInstanceNameResolver(this);
     541              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
     542              : 
     543            0 :     mSetUpCodePairer.SetSystemLayer(mSystemState->SystemLayer());
     544              : #if CONFIG_NETWORK_LAYER_BLE
     545            0 :     mSetUpCodePairer.SetBleLayer(mSystemState->BleLayer());
     546              : #endif // CONFIG_NETWORK_LAYER_BLE
     547              : 
     548            0 :     return CHIP_NO_ERROR;
     549              : }
     550              : 
     551            0 : void DeviceCommissioner::Shutdown()
     552              : {
     553            0 :     VerifyOrReturn(mState != State::NotInitialized);
     554              : 
     555            0 :     ChipLogDetail(Controller, "Shutting down the commissioner");
     556              : 
     557            0 :     mSetUpCodePairer.StopPairing();
     558              : 
     559              :     // Check to see if pairing in progress before shutting down
     560            0 :     CommissioneeDeviceProxy * device = mDeviceInPASEEstablishment;
     561            0 :     if (device != nullptr && device->IsSessionSetupInProgress())
     562              :     {
     563            0 :         ChipLogDetail(Controller, "Setup in progress, stopping setup before shutting down");
     564            0 :         OnSessionEstablishmentError(CHIP_ERROR_CONNECTION_ABORTED);
     565              :     }
     566              : 
     567            0 :     CancelCommissioningInteractions();
     568              : 
     569              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
     570              :     if (mUdcTransportMgr != nullptr)
     571              :     {
     572              :         chip::Platform::Delete(mUdcTransportMgr);
     573              :         mUdcTransportMgr = nullptr;
     574              :     }
     575              :     if (mUdcServer != nullptr)
     576              :     {
     577              :         mUdcServer->SetInstanceNameResolver(nullptr);
     578              :         chip::Platform::Delete(mUdcServer);
     579              :         mUdcServer = nullptr;
     580              :     }
     581              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
     582              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     583            0 :     WiFiPAF::WiFiPAFLayer::GetWiFiPAFLayer().Shutdown();
     584              : #endif
     585              : 
     586              :     // Release everything from the commissionee device pool here.
     587              :     // Make sure to use ReleaseCommissioneeDevice so we don't keep dangling
     588              :     // pointers to the device objects.
     589            0 :     mCommissioneeDevicePool.ForEachActiveObject([this](auto * commissioneeDevice) {
     590            0 :         ReleaseCommissioneeDevice(commissioneeDevice);
     591            0 :         return Loop::Continue;
     592              :     });
     593              : 
     594            0 :     DeviceController::Shutdown();
     595              : }
     596              : 
     597            0 : CommissioneeDeviceProxy * DeviceCommissioner::FindCommissioneeDevice(NodeId id)
     598              : {
     599              :     MATTER_TRACE_SCOPE("FindCommissioneeDevice", "DeviceCommissioner");
     600            0 :     CommissioneeDeviceProxy * foundDevice = nullptr;
     601            0 :     mCommissioneeDevicePool.ForEachActiveObject([&](auto * deviceProxy) {
     602            0 :         if (deviceProxy->GetDeviceId() == id || deviceProxy->GetTemporaryCommissioningId() == id)
     603              :         {
     604            0 :             foundDevice = deviceProxy;
     605            0 :             return Loop::Break;
     606              :         }
     607            0 :         return Loop::Continue;
     608              :     });
     609              : 
     610            0 :     return foundDevice;
     611              : }
     612              : 
     613            0 : CommissioneeDeviceProxy * DeviceCommissioner::FindCommissioneeDevice(const Transport::PeerAddress & peerAddress)
     614              : {
     615            0 :     CommissioneeDeviceProxy * foundDevice = nullptr;
     616            0 :     mCommissioneeDevicePool.ForEachActiveObject([&](auto * deviceProxy) {
     617            0 :         if (deviceProxy->GetPeerAddress() == peerAddress)
     618              :         {
     619            0 :             foundDevice = deviceProxy;
     620            0 :             return Loop::Break;
     621              :         }
     622            0 :         return Loop::Continue;
     623              :     });
     624              : 
     625            0 :     return foundDevice;
     626              : }
     627              : 
     628            0 : void DeviceCommissioner::ReleaseCommissioneeDevice(CommissioneeDeviceProxy * device)
     629              : {
     630              : #if CONFIG_NETWORK_LAYER_BLE
     631            0 :     if (mSystemState->BleLayer() != nullptr && device->GetDeviceTransportType() == Transport::Type::kBle)
     632              :     {
     633              :         // We only support one BLE connection, so if this is BLE, close it
     634            0 :         ChipLogProgress(Discovery, "Closing all BLE connections");
     635            0 :         mSystemState->BleLayer()->CloseAllBleConnections();
     636              :     }
     637              : #endif
     638              : 
     639              : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
     640              :     Nfc::NFCReaderTransport * readerTransport = DeviceLayer::Internal::NFCCommissioningMgr().GetNFCReaderTransport();
     641              :     if (readerTransport)
     642              :     {
     643              :         ChipLogProgress(Controller, "Stopping discovery of all NFC tags");
     644              :         TEMPORARY_RETURN_IGNORED readerTransport->StopDiscoveringTags();
     645              :     }
     646              : #endif
     647              : 
     648              :     // Make sure that there will be no dangling pointer
     649            0 :     if (mDeviceInPASEEstablishment == device)
     650              :     {
     651            0 :         mDeviceInPASEEstablishment = nullptr;
     652              :     }
     653            0 :     if (mDeviceBeingCommissioned == device)
     654              :     {
     655            0 :         mDeviceBeingCommissioned = nullptr;
     656              :     }
     657              : 
     658              :     // Release the commissionee device after we have nulled out our pointers,
     659              :     // because that can call back in to us with error notifications as the
     660              :     // session is released.
     661            0 :     mCommissioneeDevicePool.ReleaseObject(device);
     662            0 : }
     663              : 
     664            0 : CHIP_ERROR DeviceCommissioner::GetDeviceBeingCommissioned(NodeId deviceId, CommissioneeDeviceProxy ** out_device)
     665              : {
     666            0 :     VerifyOrReturnError(out_device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     667            0 :     CommissioneeDeviceProxy * device = FindCommissioneeDevice(deviceId);
     668              : 
     669            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     670              : 
     671            0 :     *out_device = device;
     672              : 
     673            0 :     return CHIP_NO_ERROR;
     674              : }
     675              : 
     676            0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, const char * setUpCode, const CommissioningParameters & params,
     677              :                                           DiscoveryType discoveryType, Optional<Dnssd::CommonResolutionData> resolutionData)
     678              : {
     679              :     MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
     680              : 
     681            0 :     ReturnErrorOnFailure(mDefaultCommissioner->SetCommissioningParameters(params));
     682              : 
     683            0 :     return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kCommission, discoveryType,
     684            0 :                                        resolutionData);
     685              : }
     686              : 
     687            0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, const char * setUpCode, DiscoveryType discoveryType,
     688              :                                           Optional<Dnssd::CommonResolutionData> resolutionData)
     689              : {
     690              :     MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
     691            0 :     return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kCommission, discoveryType,
     692            0 :                                        resolutionData);
     693              : }
     694              : 
     695            0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParameters & params)
     696              : {
     697              :     MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
     698            0 :     ReturnErrorOnFailureWithMetric(kMetricDeviceCommissionerCommission, EstablishPASEConnection(remoteDeviceId, params));
     699            0 :     auto errorCode = Commission(remoteDeviceId);
     700            0 :     VerifyOrDoWithMetric(kMetricDeviceCommissionerCommission, CHIP_NO_ERROR == errorCode, errorCode);
     701            0 :     return errorCode;
     702              : }
     703              : 
     704              : #if CHIP_SUPPORT_THREAD_MESHCOP
     705            0 : CHIP_ERROR DeviceCommissioner::PairThreadMeshcop(RendezvousParameters & rendezvousParams,
     706              :                                                  CommissioningParameters & commissioningParams)
     707              : {
     708            0 :     VerifyOrReturnError(rendezvousParams.GetSetupDiscriminator().has_value(), CHIP_ERROR_INVALID_ARGUMENT);
     709            0 :     VerifyOrReturnError(commissioningParams.GetThreadOperationalDataset().HasValue(), CHIP_ERROR_INVALID_ARGUMENT);
     710            0 :     auto discriminator = rendezvousParams.GetSetupDiscriminator().value();
     711            0 :     Thread::DiscoveryCode code;
     712            0 :     if (rendezvousParams.GetSetupDiscriminator().value().IsShortDiscriminator())
     713              :     {
     714            0 :         code = Thread::DiscoveryCode(discriminator.GetShortValue());
     715            0 :         ChipLogProgress(Controller, "Discovery code from short discriminator: 0x%" PRIx64, code.AsUInt64());
     716              :     }
     717              :     else
     718              :     {
     719            0 :         code = Thread::DiscoveryCode(discriminator.GetLongValue());
     720            0 :         ChipLogProgress(Controller, "Discovery code from long discriminator: 0x%" PRIx64, code.AsUInt64());
     721              :     }
     722              : 
     723              :     uint8_t pskcBuffer[Thread::kSizePSKc];
     724            0 :     ByteSpan pskc(pskcBuffer);
     725              :     {
     726            0 :         Thread::OperationalDatasetView dataset;
     727            0 :         ReturnErrorOnFailure(dataset.Init(commissioningParams.GetThreadOperationalDataset().Value()));
     728              : 
     729            0 :         ReturnErrorOnFailure(dataset.GetPSKc(pskcBuffer));
     730              :     }
     731              : 
     732              :     {
     733            0 :         Dnssd::DiscoveredNodeData discoveredNodeData;
     734            0 :         ReturnErrorOnFailure(mThreadMeshcopCommissionProxy.Discover(pskc, rendezvousParams.GetPeerAddress(), code, discriminator,
     735              :                                                                     discoveredNodeData, 30));
     736              : 
     737            0 :         ChipLogProgress(Controller, "Joiner discovered");
     738            0 :         OnNodeDiscovered(discoveredNodeData);
     739            0 :     }
     740            0 :     return CHIP_NO_ERROR;
     741              : }
     742              : #endif // CHIP_SUPPORT_THREAD_MESHCOP
     743              : 
     744            0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParameters & rendezvousParams,
     745              :                                           CommissioningParameters & commissioningParams)
     746              : {
     747              :     MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
     748              : #if CHIP_SUPPORT_THREAD_MESHCOP
     749            0 :     if (rendezvousParams.GetPeerAddress().GetTransportType() == Transport::Type::kThreadMeshcop)
     750              :     {
     751            0 :         return PairThreadMeshcop(rendezvousParams, commissioningParams);
     752              :     }
     753              : #endif
     754            0 :     ReturnErrorOnFailureWithMetric(kMetricDeviceCommissionerCommission, EstablishPASEConnection(remoteDeviceId, rendezvousParams));
     755            0 :     auto errorCode = Commission(remoteDeviceId, commissioningParams);
     756            0 :     VerifyOrDoWithMetric(kMetricDeviceCommissionerCommission, CHIP_NO_ERROR == errorCode, errorCode);
     757            0 :     return errorCode;
     758              : }
     759              : 
     760            0 : CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, const char * setUpCode, DiscoveryType discoveryType,
     761              :                                                        Optional<Dnssd::CommonResolutionData> resolutionData)
     762              : {
     763              :     MATTER_TRACE_SCOPE("EstablishPASEConnection", "DeviceCommissioner");
     764            0 :     return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kPaseOnly, discoveryType,
     765            0 :                                        resolutionData);
     766              : }
     767              : 
     768            0 : CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, RendezvousParameters & params)
     769              : {
     770              :     MATTER_TRACE_SCOPE("EstablishPASEConnection", "DeviceCommissioner");
     771              :     MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissionerPASESession);
     772              : 
     773            0 :     CHIP_ERROR err                     = CHIP_NO_ERROR;
     774            0 :     CommissioneeDeviceProxy * device   = nullptr;
     775            0 :     CommissioneeDeviceProxy * current  = nullptr;
     776            0 :     Transport::PeerAddress peerAddress = Transport::PeerAddress::UDP(Inet::IPAddress::Any);
     777              : 
     778            0 :     Messaging::ExchangeContext * exchangeCtxt = nullptr;
     779            0 :     Optional<SessionHandle> session;
     780              : 
     781            0 :     VerifyOrExit(mState == State::Initialized, err = CHIP_ERROR_INCORRECT_STATE);
     782            0 :     VerifyOrExit(mDeviceInPASEEstablishment == nullptr, err = CHIP_ERROR_INCORRECT_STATE);
     783              : 
     784              :     // TODO(#13940): We need to specify the peer address for BLE transport in bindings.
     785            0 :     if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle ||
     786            0 :         params.GetPeerAddress().GetTransportType() == Transport::Type::kUndefined)
     787              :     {
     788              : #if CONFIG_NETWORK_LAYER_BLE
     789              : #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
     790              :         ConnectBleTransportToSelf();
     791              : #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
     792            0 :         if (!params.HasBleLayer())
     793              :         {
     794            0 :             params.SetPeerAddress(Transport::PeerAddress::BLE());
     795              :         }
     796            0 :         peerAddress = Transport::PeerAddress::BLE();
     797              : #endif // CONFIG_NETWORK_LAYER_BLE
     798              :     }
     799            0 :     else if (params.GetPeerAddress().GetTransportType() == Transport::Type::kTcp ||
     800            0 :              params.GetPeerAddress().GetTransportType() == Transport::Type::kUdp)
     801              :     {
     802            0 :         peerAddress = Transport::PeerAddress::UDP(params.GetPeerAddress().GetIPAddress(), params.GetPeerAddress().GetPort(),
     803            0 :                                                   params.GetPeerAddress().GetInterface());
     804              :     }
     805              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     806            0 :     else if (params.GetPeerAddress().GetTransportType() == Transport::Type::kWiFiPAF)
     807              :     {
     808            0 :         peerAddress = Transport::PeerAddress::WiFiPAF(remoteDeviceId);
     809              :     }
     810              : #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     811              : 
     812            0 :     current = FindCommissioneeDevice(peerAddress);
     813            0 :     if (current != nullptr)
     814              :     {
     815            0 :         if (current->GetDeviceId() == remoteDeviceId)
     816              :         {
     817              :             // We might be able to just reuse its connection if it has one or is
     818              :             // working on one.
     819            0 :             if (current->IsSecureConnected())
     820              :             {
     821            0 :                 if (mPairingDelegate)
     822              :                 {
     823              :                     // We already have an open secure session to this device, call the callback immediately and early return.
     824              :                     // We don't know what the right RendezvousParameters are here.
     825            0 :                     mPairingDelegate->OnPairingComplete(CHIP_NO_ERROR, std::nullopt, std::nullopt);
     826              :                 }
     827              :                 MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, CHIP_NO_ERROR);
     828            0 :                 return CHIP_NO_ERROR;
     829              :             }
     830            0 :             if (current->IsSessionSetupInProgress())
     831              :             {
     832              :                 // We're not connected yet, but we're in the process of connecting. Pairing delegate will get a callback when
     833              :                 // connection completes
     834            0 :                 return CHIP_NO_ERROR;
     835              :             }
     836              :         }
     837              : 
     838              :         // Either the consumer wants to assign a different device id to this
     839              :         // peer address now (so we can't reuse the commissionee device we have
     840              :         // already) or something has gone strange. Delete the old device, try
     841              :         // again.
     842            0 :         ChipLogError(Controller, "Found unconnected device, removing");
     843            0 :         ReleaseCommissioneeDevice(current);
     844              :     }
     845              : 
     846            0 :     device = mCommissioneeDevicePool.CreateObject();
     847            0 :     VerifyOrExit(device != nullptr, err = CHIP_ERROR_NO_MEMORY);
     848              : 
     849            0 :     mDeviceInPASEEstablishment = device;
     850            0 :     device->Init(GetControllerDeviceInitParams(), remoteDeviceId, peerAddress);
     851            0 :     device->UpdateDeviceData(params.GetPeerAddress(), params.GetMRPConfig());
     852              : 
     853              : #if CONFIG_NETWORK_LAYER_BLE
     854            0 :     if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle)
     855              :     {
     856            0 :         if (params.HasConnectionObject())
     857              :         {
     858            0 :             SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByObject(params.GetConnectionObject()));
     859              :         }
     860            0 :         else if (params.HasDiscoveredObject())
     861              :         {
     862              :             // The RendezvousParameters argument needs to be recovered if the search succeed, so save them
     863              :             // for later.
     864            0 :             mRendezvousParametersForDeviceDiscoveredOverBle = params;
     865            0 :             ExitNow(err = mSystemState->BleLayer()->NewBleConnectionByObject(
     866              :                         params.GetDiscoveredObject(), this, OnDiscoveredDeviceOverBleSuccess, OnDiscoveredDeviceOverBleError));
     867              :         }
     868            0 :         else if (params.HasDiscriminator())
     869              :         {
     870              :             // The RendezvousParameters argument needs to be recovered if the search succeed, so save them
     871              :             // for later.
     872            0 :             mRendezvousParametersForDeviceDiscoveredOverBle = params;
     873            0 :             auto setupDiscriminator                         = params.GetSetupDiscriminator();
     874            0 :             VerifyOrExit(setupDiscriminator.has_value(), err = CHIP_ERROR_INVALID_ARGUMENT);
     875            0 :             ExitNow(err = mSystemState->BleLayer()->NewBleConnectionByDiscriminator(
     876              :                         setupDiscriminator.value(), this, OnDiscoveredDeviceOverBleSuccess, OnDiscoveredDeviceOverBleError));
     877              :         }
     878              :         else
     879              :         {
     880            0 :             ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
     881              :         }
     882              :     }
     883              : #endif
     884              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     885            0 :     if (params.GetPeerAddress().GetTransportType() == Transport::Type::kWiFiPAF)
     886              :     {
     887            0 :         if (DeviceLayer::ConnectivityMgr().GetWiFiPAF()->GetWiFiPAFState() != WiFiPAF::State::kConnected)
     888              :         {
     889            0 :             ChipLogProgress(Controller, "WiFi-PAF: Subscribing to the NAN-USD devices, nodeId: %" PRIu64,
     890              :                             params.GetPeerAddress().GetRemoteId());
     891            0 :             mRendezvousParametersForDeviceDiscoveredOverWiFiPAF = params;
     892            0 :             auto nodeId                                         = params.GetPeerAddress().GetRemoteId();
     893            0 :             const SetupDiscriminator connDiscriminator(params.GetSetupDiscriminator().value());
     894            0 :             VerifyOrReturnValue(!connDiscriminator.IsShortDiscriminator(), CHIP_ERROR_INVALID_ARGUMENT,
     895              :                                 ChipLogError(Controller, "Error, Long discriminator is required"));
     896            0 :             uint16_t discriminator              = connDiscriminator.GetLongValue();
     897            0 :             WiFiPAF::WiFiPAFSession sessionInfo = { .role          = WiFiPAF::WiFiPafRole::kWiFiPafRole_Subscriber,
     898              :                                                     .nodeId        = nodeId,
     899            0 :                                                     .discriminator = discriminator };
     900            0 :             ReturnErrorOnFailure(
     901              :                 DeviceLayer::ConnectivityMgr().GetWiFiPAF()->AddPafSession(WiFiPAF::PafInfoAccess::kAccNodeInfo, sessionInfo));
     902            0 :             ExitNow(err = DeviceLayer::ConnectivityMgr().WiFiPAFSubscribe(discriminator, reinterpret_cast<void *>(this),
     903              :                                                                           OnWiFiPAFSubscribeComplete, OnWiFiPAFSubscribeError));
     904              :         }
     905              :     }
     906              : #endif
     907            0 :     session = mSystemState->SessionMgr()->CreateUnauthenticatedSession(params.GetPeerAddress(), params.GetMRPConfig());
     908            0 :     VerifyOrExit(session.HasValue(), err = CHIP_ERROR_NO_MEMORY);
     909              : 
     910              :     // Allocate the exchange immediately before calling PASESession::Pair.
     911              :     //
     912              :     // PASESession::Pair takes ownership of the exchange and will free it on
     913              :     // error, but can only do this if it is actually called.  Allocating the
     914              :     // exchange context right before calling Pair ensures that if allocation
     915              :     // succeeds, PASESession has taken ownership.
     916            0 :     exchangeCtxt = mSystemState->ExchangeMgr()->NewContext(session.Value(), &device->GetPairing());
     917            0 :     VerifyOrExit(exchangeCtxt != nullptr, err = CHIP_ERROR_INTERNAL);
     918              : 
     919            0 :     err = device->GetPairing().Pair(*mSystemState->SessionMgr(), params.GetSetupPINCode(), GetLocalMRPConfig(), exchangeCtxt, this);
     920            0 :     SuccessOrExit(err);
     921              : 
     922            0 :     mRendezvousParametersForPASEEstablishment = params;
     923              : 
     924            0 : exit:
     925            0 :     if (err != CHIP_NO_ERROR)
     926              :     {
     927            0 :         if (device != nullptr)
     928              :         {
     929            0 :             ReleaseCommissioneeDevice(device);
     930              :         }
     931              :         MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, err);
     932              :     }
     933              : 
     934            0 :     return err;
     935            0 : }
     936              : 
     937              : #if CONFIG_NETWORK_LAYER_BLE
     938            0 : void DeviceCommissioner::OnDiscoveredDeviceOverBleSuccess(void * appState, BLE_CONNECTION_OBJECT connObj)
     939              : {
     940            0 :     auto self   = static_cast<DeviceCommissioner *>(appState);
     941            0 :     auto device = self->mDeviceInPASEEstablishment;
     942              : 
     943            0 :     if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kBle)
     944              :     {
     945            0 :         auto remoteId = device->GetDeviceId();
     946              : 
     947            0 :         auto params = self->mRendezvousParametersForDeviceDiscoveredOverBle;
     948            0 :         params.SetConnectionObject(connObj);
     949            0 :         self->mRendezvousParametersForDeviceDiscoveredOverBle = RendezvousParameters();
     950              : 
     951            0 :         self->ReleaseCommissioneeDevice(device);
     952            0 :         LogErrorOnFailure(self->EstablishPASEConnection(remoteId, params));
     953              :     }
     954            0 : }
     955              : 
     956            0 : void DeviceCommissioner::OnDiscoveredDeviceOverBleError(void * appState, CHIP_ERROR err)
     957              : {
     958            0 :     auto self   = static_cast<DeviceCommissioner *>(appState);
     959            0 :     auto device = self->mDeviceInPASEEstablishment;
     960              : 
     961            0 :     if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kBle)
     962              :     {
     963            0 :         self->ReleaseCommissioneeDevice(device);
     964            0 :         self->mRendezvousParametersForDeviceDiscoveredOverBle = RendezvousParameters();
     965              : 
     966              :         // Callback is required when BLE discovery fails, otherwise the caller will always be in a suspended state
     967              :         // A better way to handle it should define a new error code
     968            0 :         if (self->mPairingDelegate != nullptr)
     969              :         {
     970            0 :             self->mPairingDelegate->OnPairingComplete(err, std::nullopt, std::nullopt);
     971              :         }
     972              :     }
     973            0 : }
     974              : #endif // CONFIG_NETWORK_LAYER_BLE
     975              : 
     976              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     977            0 : void DeviceCommissioner::OnWiFiPAFSubscribeComplete(void * appState)
     978              : {
     979            0 :     auto self   = reinterpret_cast<DeviceCommissioner *>(appState);
     980            0 :     auto device = self->mDeviceInPASEEstablishment;
     981              : 
     982            0 :     if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kWiFiPAF)
     983              :     {
     984            0 :         ChipLogProgress(Controller, "WiFi-PAF: Subscription Completed, dev_id = %" PRIu64, device->GetDeviceId());
     985            0 :         auto remoteId = device->GetDeviceId();
     986            0 :         auto params   = self->mRendezvousParametersForDeviceDiscoveredOverWiFiPAF;
     987              : 
     988            0 :         self->mRendezvousParametersForDeviceDiscoveredOverWiFiPAF = RendezvousParameters();
     989            0 :         self->ReleaseCommissioneeDevice(device);
     990            0 :         LogErrorOnFailure(self->EstablishPASEConnection(remoteId, params));
     991              :     }
     992            0 : }
     993              : 
     994            0 : void DeviceCommissioner::OnWiFiPAFSubscribeError(void * appState, CHIP_ERROR err)
     995              : {
     996            0 :     auto self   = (DeviceCommissioner *) appState;
     997            0 :     auto device = self->mDeviceInPASEEstablishment;
     998              : 
     999            0 :     if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kWiFiPAF)
    1000              :     {
    1001            0 :         ChipLogError(Controller, "WiFi-PAF: Subscription Error, id = %" PRIu64 ", err = %" CHIP_ERROR_FORMAT, device->GetDeviceId(),
    1002              :                      err.Format());
    1003            0 :         self->ReleaseCommissioneeDevice(device);
    1004            0 :         self->mRendezvousParametersForDeviceDiscoveredOverWiFiPAF = RendezvousParameters();
    1005            0 :         if (self->mPairingDelegate != nullptr)
    1006              :         {
    1007            0 :             self->mPairingDelegate->OnPairingComplete(err, std::nullopt, std::nullopt);
    1008              :         }
    1009              :     }
    1010            0 : }
    1011              : #endif
    1012              : 
    1013            0 : CHIP_ERROR DeviceCommissioner::Commission(NodeId remoteDeviceId, CommissioningParameters & params)
    1014              : {
    1015            0 :     ReturnErrorOnFailureWithMetric(kMetricDeviceCommissionerCommission, mDefaultCommissioner->SetCommissioningParameters(params));
    1016            0 :     auto errorCode = Commission(remoteDeviceId);
    1017            0 :     VerifyOrDoWithMetric(kMetricDeviceCommissionerCommission, CHIP_NO_ERROR == errorCode, errorCode);
    1018            0 :     return errorCode;
    1019              : }
    1020              : 
    1021            0 : CHIP_ERROR DeviceCommissioner::Commission(NodeId remoteDeviceId)
    1022              : {
    1023              :     MATTER_TRACE_SCOPE("Commission", "DeviceCommissioner");
    1024              : 
    1025              : #if CHIP_CONFIG_ENABLE_ADDRESS_RESOLVE_FALLBACK
    1026              :     // Reset fallback from any previous commissioning session
    1027              :     mFallbackOperationalResolveResult.ClearValue();
    1028              : #endif // CHIP_CONFIG_ENABLE_ADDRESS_RESOLVE_FALLBACK
    1029              : 
    1030            0 :     CommissioneeDeviceProxy * device = FindCommissioneeDevice(remoteDeviceId);
    1031            0 :     if (device == nullptr || (!device->IsSecureConnected() && !device->IsSessionSetupInProgress()))
    1032              :     {
    1033            0 :         ChipLogError(Controller, "Invalid device for commissioning " ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
    1034            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1035              :     }
    1036            0 :     if (!device->IsSecureConnected() && device != mDeviceInPASEEstablishment)
    1037              :     {
    1038              :         // We should not end up in this state because we won't attempt to establish more than one connection at a time.
    1039            0 :         ChipLogError(Controller, "Device is not connected and not being paired " ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
    1040            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1041              :     }
    1042              : 
    1043            0 :     if (mCommissioningStage != CommissioningStage::kSecurePairing)
    1044              :     {
    1045            0 :         ChipLogError(Controller, "Commissioning already in progress (stage '%s') - not restarting",
    1046              :                      StageToString(mCommissioningStage));
    1047            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1048              :     }
    1049              : 
    1050            0 :     ChipLogProgress(Controller, "Commission called for node ID 0x" ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
    1051              : 
    1052            0 :     mDefaultCommissioner->SetOperationalCredentialsDelegate(mOperationalCredentialsDelegate);
    1053            0 :     if (device->IsSecureConnected())
    1054              :     {
    1055              :         MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissionerCommission);
    1056            0 :         ReturnErrorOnFailure(mDefaultCommissioner->StartCommissioning(this, device));
    1057              :     }
    1058              :     else
    1059              :     {
    1060            0 :         mRunCommissioningAfterConnection = true;
    1061              :     }
    1062            0 :     return CHIP_NO_ERROR;
    1063              : }
    1064              : 
    1065              : CHIP_ERROR
    1066            0 : DeviceCommissioner::ContinueCommissioningAfterDeviceAttestation(DeviceProxy * device,
    1067              :                                                                 Credentials::AttestationVerificationResult attestationResult)
    1068              : {
    1069              :     MATTER_TRACE_SCOPE("continueCommissioningDevice", "DeviceCommissioner");
    1070              : 
    1071            0 :     if (device == nullptr || device != mDeviceBeingCommissioned)
    1072              :     {
    1073            0 :         ChipLogError(Controller, "Invalid device for commissioning %p", device);
    1074            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1075              :     }
    1076            0 :     CommissioneeDeviceProxy * commissioneeDevice = FindCommissioneeDevice(device->GetDeviceId());
    1077            0 :     if (commissioneeDevice == nullptr)
    1078              :     {
    1079            0 :         ChipLogError(Controller, "Couldn't find commissionee device");
    1080            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1081              :     }
    1082            0 :     if (!commissioneeDevice->IsSecureConnected() || commissioneeDevice != mDeviceBeingCommissioned)
    1083              :     {
    1084            0 :         ChipLogError(Controller, "Invalid device for commissioning after attestation failure: 0x" ChipLogFormatX64,
    1085              :                      ChipLogValueX64(commissioneeDevice->GetDeviceId()));
    1086            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1087              :     }
    1088              : 
    1089            0 :     if (mCommissioningStage != CommissioningStage::kAttestationRevocationCheck)
    1090              :     {
    1091            0 :         ChipLogError(Controller, "Commissioning is not attestation verification phase");
    1092            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1093              :     }
    1094              : 
    1095            0 :     ChipLogProgress(Controller, "Continuing commissioning after attestation failure for device ID 0x" ChipLogFormatX64,
    1096              :                     ChipLogValueX64(commissioneeDevice->GetDeviceId()));
    1097              : 
    1098            0 :     if (attestationResult != AttestationVerificationResult::kSuccess)
    1099              :     {
    1100            0 :         ChipLogError(Controller, "Client selected error: %u for failed 'Attestation Information' for device",
    1101              :                      to_underlying(attestationResult));
    1102              : 
    1103            0 :         CommissioningDelegate::CommissioningReport report;
    1104            0 :         report.Set<AttestationErrorInfo>(attestationResult);
    1105            0 :         CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
    1106            0 :     }
    1107              :     else
    1108              :     {
    1109            0 :         ChipLogProgress(Controller, "Overriding attestation failure per client and continuing commissioning");
    1110            0 :         CommissioningStageComplete(CHIP_NO_ERROR);
    1111              :     }
    1112            0 :     return CHIP_NO_ERROR;
    1113              : }
    1114              : 
    1115              : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
    1116              : CHIP_ERROR DeviceCommissioner::ContinueCommissioningAfterConnectNetworkRequest(NodeId remoteDeviceId)
    1117              : {
    1118              :     MATTER_TRACE_SCOPE("continueCommissioningAfterConnectNetworkRequest", "DeviceCommissioner");
    1119              : 
    1120              :     // Move to kEvictPreviousCaseSessions stage since the next stage will be to find the device
    1121              :     // on the operational network
    1122              :     mCommissioningStage = CommissioningStage::kEvictPreviousCaseSessions;
    1123              : 
    1124              :     // Setup device being commissioned
    1125              :     CommissioneeDeviceProxy * device = nullptr;
    1126              :     if (!mDeviceBeingCommissioned)
    1127              :     {
    1128              :         device = mCommissioneeDevicePool.CreateObject();
    1129              :         if (!device)
    1130              :             return CHIP_ERROR_NO_MEMORY;
    1131              : 
    1132              :         Transport::PeerAddress peerAddress = Transport::PeerAddress::UDP(Inet::IPAddress::Any);
    1133              :         device->Init(GetControllerDeviceInitParams(), remoteDeviceId, peerAddress);
    1134              :         mDeviceBeingCommissioned = device;
    1135              :     }
    1136              : 
    1137              :     mDefaultCommissioner->SetOperationalCredentialsDelegate(mOperationalCredentialsDelegate);
    1138              : 
    1139              :     ChipLogProgress(Controller, "Continuing commissioning after connect to network complete for device ID 0x" ChipLogFormatX64,
    1140              :                     ChipLogValueX64(remoteDeviceId));
    1141              : 
    1142              :     MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissioningOperationalSetup);
    1143              :     CHIP_ERROR err = mDefaultCommissioner->StartCommissioning(this, device);
    1144              :     if (err != CHIP_NO_ERROR)
    1145              :     {
    1146              :         MATTER_LOG_METRIC_END(kMetricDeviceCommissioningOperationalSetup, err);
    1147              :     }
    1148              :     return err;
    1149              : }
    1150              : #endif
    1151              : 
    1152            0 : CHIP_ERROR DeviceCommissioner::StopPairing(NodeId remoteDeviceId)
    1153              : {
    1154            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1155            0 :     VerifyOrReturnError(remoteDeviceId != kUndefinedNodeId, CHIP_ERROR_INVALID_ARGUMENT);
    1156              : 
    1157            0 :     ChipLogProgress(Controller, "StopPairing called for node ID 0x" ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
    1158              : 
    1159              :     // If we're still in the process of discovering the device, just stop the SetUpCodePairer
    1160            0 :     if (mSetUpCodePairer.StopPairing(remoteDeviceId))
    1161              :     {
    1162            0 :         mRunCommissioningAfterConnection = false;
    1163            0 :         OnSessionEstablishmentError(CHIP_ERROR_CANCELLED);
    1164            0 :         return CHIP_NO_ERROR;
    1165              :     }
    1166              : 
    1167              :     // Otherwise we might be pairing and / or commissioning it.
    1168            0 :     CommissioneeDeviceProxy * device = FindCommissioneeDevice(remoteDeviceId);
    1169            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_DEVICE_DESCRIPTOR);
    1170              : 
    1171            0 :     if (mDeviceBeingCommissioned == device)
    1172              :     {
    1173            0 :         CancelCommissioningInteractions();
    1174            0 :         CommissioningStageComplete(CHIP_ERROR_CANCELLED);
    1175              :     }
    1176              :     else
    1177              :     {
    1178            0 :         ReleaseCommissioneeDevice(device);
    1179              :     }
    1180            0 :     return CHIP_NO_ERROR;
    1181              : }
    1182              : 
    1183            0 : void DeviceCommissioner::CancelCommissioningInteractions()
    1184              : {
    1185            0 :     if (mReadClient)
    1186              :     {
    1187            0 :         ChipLogDetail(Controller, "Cancelling read request for step '%s'", StageToString(mCommissioningStage));
    1188            0 :         mReadClient.reset(); // destructor cancels
    1189            0 :         mAttributeCache.reset();
    1190              :     }
    1191            0 :     if (mInvokeCancelFn)
    1192              :     {
    1193            0 :         ChipLogDetail(Controller, "Cancelling command invocation for step '%s'", StageToString(mCommissioningStage));
    1194            0 :         mInvokeCancelFn();
    1195            0 :         mInvokeCancelFn = nullptr;
    1196              :     }
    1197            0 :     if (mWriteCancelFn)
    1198              :     {
    1199            0 :         ChipLogDetail(Controller, "Cancelling write request for step '%s'", StageToString(mCommissioningStage));
    1200            0 :         mWriteCancelFn();
    1201            0 :         mWriteCancelFn = nullptr;
    1202              :     }
    1203            0 :     if (mOnDeviceConnectedCallback.IsRegistered())
    1204              :     {
    1205            0 :         ChipLogDetail(Controller, "Cancelling CASE setup for step '%s'", StageToString(mCommissioningStage));
    1206            0 :         CancelCASECallbacks();
    1207              :     }
    1208            0 : }
    1209              : 
    1210            0 : void DeviceCommissioner::CancelCASECallbacks()
    1211              : {
    1212            0 :     mOnDeviceConnectedCallback.Cancel();
    1213            0 :     mOnDeviceConnectionFailureCallback.Cancel();
    1214              : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    1215            0 :     mOnDeviceConnectionRetryCallback.Cancel();
    1216              : #endif
    1217            0 : }
    1218              : 
    1219            0 : CHIP_ERROR DeviceCommissioner::UnpairDevice(NodeId remoteDeviceId)
    1220              : {
    1221              :     MATTER_TRACE_SCOPE("UnpairDevice", "DeviceCommissioner");
    1222            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1223              : 
    1224            0 :     return AutoCurrentFabricRemover::RemoveCurrentFabric(this, remoteDeviceId);
    1225              : }
    1226              : 
    1227            1 : void DeviceCommissioner::RendezvousCleanup(CHIP_ERROR status)
    1228              : {
    1229            1 :     if (mDeviceInPASEEstablishment != nullptr)
    1230              :     {
    1231              :         // Release the commissionee device. For BLE, this is stored,
    1232              :         // for IP commissioning, we have taken a reference to the
    1233              :         // operational node to send the completion command.
    1234            0 :         ReleaseCommissioneeDevice(mDeviceInPASEEstablishment);
    1235              : 
    1236            0 :         if (mPairingDelegate != nullptr)
    1237              :         {
    1238            0 :             mPairingDelegate->OnPairingComplete(status, std::nullopt, std::nullopt);
    1239              :         }
    1240              :     }
    1241            1 : }
    1242              : 
    1243            1 : void DeviceCommissioner::OnSessionEstablishmentError(CHIP_ERROR err)
    1244              : {
    1245              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, err);
    1246              : 
    1247            1 :     mRendezvousParametersForPASEEstablishment.reset();
    1248              : 
    1249            1 :     if (mPairingDelegate != nullptr)
    1250              :     {
    1251            0 :         mPairingDelegate->OnStatusUpdate(DevicePairingDelegate::SecurePairingFailed);
    1252              :     }
    1253              : 
    1254            1 :     RendezvousCleanup(err);
    1255            1 : }
    1256              : 
    1257            0 : void DeviceCommissioner::OnSessionEstablished(const SessionHandle & session)
    1258              : {
    1259              :     // PASE session established.
    1260            0 :     CommissioneeDeviceProxy * device = mDeviceInPASEEstablishment;
    1261              : 
    1262              :     // We are in the callback for this pairing. Reset so we can pair another device.
    1263            0 :     mDeviceInPASEEstablishment = nullptr;
    1264              : 
    1265              :     // Make sure to clear out mRendezvousParametersForPASEEstablishment no
    1266              :     // matter what.
    1267            0 :     std::optional<RendezvousParameters> paseParameters;
    1268            0 :     paseParameters.swap(mRendezvousParametersForPASEEstablishment);
    1269              : 
    1270            0 :     VerifyOrReturn(device != nullptr, OnSessionEstablishmentError(CHIP_ERROR_INVALID_DEVICE_DESCRIPTOR));
    1271              : 
    1272            0 :     CHIP_ERROR err = device->SetConnected(session);
    1273            0 :     if (err != CHIP_NO_ERROR)
    1274              :     {
    1275            0 :         ChipLogError(Controller, "Failed in setting up secure channel: %" CHIP_ERROR_FORMAT, err.Format());
    1276            0 :         OnSessionEstablishmentError(err);
    1277            0 :         return;
    1278              :     }
    1279              : 
    1280            0 :     ChipLogDetail(Controller, "Remote device completed SPAKE2+ handshake");
    1281              : 
    1282              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, CHIP_NO_ERROR);
    1283            0 :     if (mPairingDelegate != nullptr)
    1284              :     {
    1285              :         // If we started with a string payload, then at this point mPairingDelegate is
    1286              :         // mSetUpCodePairer, and it will provide the right SetupPayload argument to
    1287              :         // OnPairingComplete as needed.  If mPairingDelegate is not
    1288              :         // mSetUpCodePairer, then we don't have a SetupPayload to provide.
    1289            0 :         mPairingDelegate->OnPairingComplete(CHIP_NO_ERROR, paseParameters, std::nullopt);
    1290              :     }
    1291              : 
    1292            0 :     if (mRunCommissioningAfterConnection)
    1293              :     {
    1294            0 :         mRunCommissioningAfterConnection = false;
    1295              :         MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissionerCommission);
    1296            0 :         ReturnAndLogOnFailure(mDefaultCommissioner->StartCommissioning(this, device), Controller, "Failed to start commissioning");
    1297              :     }
    1298              : }
    1299              : 
    1300            0 : CHIP_ERROR DeviceCommissioner::SendCertificateChainRequestCommand(DeviceProxy * device,
    1301              :                                                                   Credentials::CertificateType certificateType,
    1302              :                                                                   Optional<System::Clock::Timeout> timeout)
    1303              : {
    1304              :     MATTER_TRACE_SCOPE("SendCertificateChainRequestCommand", "DeviceCommissioner");
    1305            0 :     ChipLogDetail(Controller, "Sending Certificate Chain request to %p device", device);
    1306            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1307              : 
    1308            0 :     OperationalCredentials::Commands::CertificateChainRequest::Type request;
    1309            0 :     request.certificateType = static_cast<OperationalCredentials::CertificateChainTypeEnum>(certificateType);
    1310            0 :     return SendCommissioningCommand(device, request, OnCertificateChainResponse, OnCertificateChainFailureResponse, kRootEndpointId,
    1311            0 :                                     timeout);
    1312              : }
    1313              : 
    1314            0 : void DeviceCommissioner::OnCertificateChainFailureResponse(void * context, CHIP_ERROR error)
    1315              : {
    1316              :     MATTER_TRACE_SCOPE("OnCertificateChainFailureResponse", "DeviceCommissioner");
    1317            0 :     ChipLogProgress(Controller, "Device failed to receive the Certificate Chain request Response: %" CHIP_ERROR_FORMAT,
    1318              :                     error.Format());
    1319            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1320            0 :     commissioner->CommissioningStageComplete(error);
    1321            0 : }
    1322              : 
    1323            0 : void DeviceCommissioner::OnCertificateChainResponse(
    1324              :     void * context, const chip::app::Clusters::OperationalCredentials::Commands::CertificateChainResponse::DecodableType & response)
    1325              : {
    1326              :     MATTER_TRACE_SCOPE("OnCertificateChainResponse", "DeviceCommissioner");
    1327            0 :     ChipLogProgress(Controller, "Received certificate chain from the device");
    1328            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1329              : 
    1330            0 :     CommissioningDelegate::CommissioningReport report;
    1331            0 :     report.Set<RequestedCertificate>(RequestedCertificate(response.certificate));
    1332              : 
    1333            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    1334            0 : }
    1335              : 
    1336            0 : CHIP_ERROR DeviceCommissioner::SendAttestationRequestCommand(DeviceProxy * device, const ByteSpan & attestationNonce,
    1337              :                                                              Optional<System::Clock::Timeout> timeout)
    1338              : {
    1339              :     MATTER_TRACE_SCOPE("SendAttestationRequestCommand", "DeviceCommissioner");
    1340            0 :     ChipLogDetail(Controller, "Sending Attestation request to %p device", device);
    1341            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1342              : 
    1343            0 :     OperationalCredentials::Commands::AttestationRequest::Type request;
    1344            0 :     request.attestationNonce = attestationNonce;
    1345              : 
    1346            0 :     ReturnErrorOnFailure(
    1347              :         SendCommissioningCommand(device, request, OnAttestationResponse, OnAttestationFailureResponse, kRootEndpointId, timeout));
    1348            0 :     ChipLogDetail(Controller, "Sent Attestation request, waiting for the Attestation Information");
    1349            0 :     return CHIP_NO_ERROR;
    1350              : }
    1351              : 
    1352            0 : void DeviceCommissioner::OnAttestationFailureResponse(void * context, CHIP_ERROR error)
    1353              : {
    1354              :     MATTER_TRACE_SCOPE("OnAttestationFailureResponse", "DeviceCommissioner");
    1355            0 :     ChipLogProgress(Controller, "Device failed to receive the Attestation Information Response: %" CHIP_ERROR_FORMAT,
    1356              :                     error.Format());
    1357            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1358            0 :     commissioner->CommissioningStageComplete(error);
    1359            0 : }
    1360              : 
    1361            0 : void DeviceCommissioner::OnAttestationResponse(void * context,
    1362              :                                                const OperationalCredentials::Commands::AttestationResponse::DecodableType & data)
    1363              : {
    1364              :     MATTER_TRACE_SCOPE("OnAttestationResponse", "DeviceCommissioner");
    1365            0 :     ChipLogProgress(Controller, "Received Attestation Information from the device");
    1366            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1367              : 
    1368            0 :     CommissioningDelegate::CommissioningReport report;
    1369            0 :     report.Set<AttestationResponse>(AttestationResponse(data.attestationElements, data.attestationSignature));
    1370            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    1371            0 : }
    1372              : 
    1373            0 : void DeviceCommissioner::OnDeviceAttestationInformationVerification(
    1374              :     void * context, const Credentials::DeviceAttestationVerifier::AttestationInfo & info, AttestationVerificationResult result)
    1375              : {
    1376              :     MATTER_TRACE_SCOPE("OnDeviceAttestationInformationVerification", "DeviceCommissioner");
    1377            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1378              : 
    1379            0 :     if (commissioner->mCommissioningStage == CommissioningStage::kAttestationVerification)
    1380              :     {
    1381              :         // Check for revoked DAC Chain before calling delegate. Enter next stage.
    1382              : 
    1383            0 :         CommissioningDelegate::CommissioningReport report;
    1384            0 :         report.Set<AttestationErrorInfo>(result);
    1385              : 
    1386            0 :         return commissioner->CommissioningStageComplete(
    1387            0 :             result == AttestationVerificationResult::kSuccess ? CHIP_NO_ERROR : CHIP_ERROR_FAILED_DEVICE_ATTESTATION, report);
    1388            0 :     }
    1389              : 
    1390            0 :     if (!commissioner->mDeviceBeingCommissioned)
    1391              :     {
    1392            0 :         ChipLogError(Controller, "Device attestation verification result received when we're not commissioning a device");
    1393            0 :         return;
    1394              :     }
    1395              : 
    1396            0 :     auto & params = commissioner->mDefaultCommissioner->GetCommissioningParameters();
    1397            0 :     Credentials::DeviceAttestationDelegate * deviceAttestationDelegate = params.GetDeviceAttestationDelegate();
    1398              : 
    1399            0 :     if (params.GetCompletionStatus().attestationResult.HasValue())
    1400              :     {
    1401            0 :         auto previousResult = params.GetCompletionStatus().attestationResult.Value();
    1402            0 :         if (previousResult != AttestationVerificationResult::kSuccess)
    1403              :         {
    1404            0 :             result = previousResult;
    1405              :         }
    1406              :     }
    1407              : 
    1408            0 :     if (result != AttestationVerificationResult::kSuccess)
    1409              :     {
    1410            0 :         CommissioningDelegate::CommissioningReport report;
    1411            0 :         report.Set<AttestationErrorInfo>(result);
    1412            0 :         if (result == AttestationVerificationResult::kNotImplemented)
    1413              :         {
    1414            0 :             ChipLogError(Controller,
    1415              :                          "Failed in verifying 'Attestation Information' command received from the device due to default "
    1416              :                          "DeviceAttestationVerifier Class not being overridden by a real implementation.");
    1417            0 :             commissioner->CommissioningStageComplete(CHIP_ERROR_NOT_IMPLEMENTED, report);
    1418            0 :             return;
    1419              :         }
    1420              : 
    1421            0 :         ChipLogError(Controller, "Failed in verifying 'Attestation Information' command received from the device: err %hu (%s)",
    1422              :                      static_cast<uint16_t>(result), GetAttestationResultDescription(result));
    1423              :         // Go look at AttestationVerificationResult enum in src/credentials/attestation_verifier/DeviceAttestationVerifier.h to
    1424              :         // understand the errors.
    1425              : 
    1426              :         // If a device attestation status delegate is installed, delegate handling of failure to the client and let them
    1427              :         // decide on whether to proceed further or not.
    1428            0 :         if (deviceAttestationDelegate)
    1429              :         {
    1430            0 :             commissioner->ExtendArmFailSafeForDeviceAttestation(info, result);
    1431              :         }
    1432              :         else
    1433              :         {
    1434            0 :             commissioner->CommissioningStageComplete(CHIP_ERROR_FAILED_DEVICE_ATTESTATION, report);
    1435              :         }
    1436            0 :     }
    1437              :     else
    1438              :     {
    1439            0 :         if (deviceAttestationDelegate && deviceAttestationDelegate->ShouldWaitAfterDeviceAttestation())
    1440              :         {
    1441            0 :             commissioner->ExtendArmFailSafeForDeviceAttestation(info, result);
    1442              :         }
    1443              :         else
    1444              :         {
    1445            0 :             ChipLogProgress(Controller, "Successfully validated 'Attestation Information' command received from the device.");
    1446            0 :             commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    1447              :         }
    1448              :     }
    1449              : }
    1450              : 
    1451            0 : void DeviceCommissioner::OnArmFailSafeExtendedForDeviceAttestation(
    1452              :     void * context, const GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType &)
    1453              : {
    1454            0 :     ChipLogProgress(Controller, "Successfully extended fail-safe timer to handle DA failure");
    1455            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1456              : 
    1457              :     // We have completed our command invoke, but we're not going to finish the
    1458              :     // commissioning step until our client examines the attestation
    1459              :     // information.  Clear out mInvokeCancelFn (which points at the
    1460              :     // CommandSender we just finished using) now, so it's not dangling.
    1461            0 :     commissioner->mInvokeCancelFn = nullptr;
    1462              : 
    1463            0 :     commissioner->HandleDeviceAttestationCompleted();
    1464            0 : }
    1465              : 
    1466            0 : void DeviceCommissioner::HandleDeviceAttestationCompleted()
    1467              : {
    1468            0 :     if (!mDeviceBeingCommissioned)
    1469              :     {
    1470            0 :         return;
    1471              :     }
    1472              : 
    1473            0 :     auto & params                                                      = mDefaultCommissioner->GetCommissioningParameters();
    1474            0 :     Credentials::DeviceAttestationDelegate * deviceAttestationDelegate = params.GetDeviceAttestationDelegate();
    1475            0 :     if (deviceAttestationDelegate)
    1476              :     {
    1477            0 :         ChipLogProgress(Controller, "Device attestation completed, delegating continuation to client");
    1478            0 :         deviceAttestationDelegate->OnDeviceAttestationCompleted(this, mDeviceBeingCommissioned, *mAttestationDeviceInfo,
    1479              :                                                                 mAttestationResult);
    1480              :     }
    1481              :     else
    1482              :     {
    1483            0 :         ChipLogError(Controller, "Need to wait for device attestation delegate, but no delegate available. Failing commissioning");
    1484            0 :         CommissioningDelegate::CommissioningReport report;
    1485            0 :         report.Set<AttestationErrorInfo>(mAttestationResult);
    1486            0 :         CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
    1487            0 :     }
    1488              : }
    1489              : 
    1490            0 : void DeviceCommissioner::OnFailedToExtendedArmFailSafeDeviceAttestation(void * context, CHIP_ERROR error)
    1491              : {
    1492            0 :     ChipLogProgress(Controller, "Failed to extend fail-safe timer to handle attestation failure: %" CHIP_ERROR_FORMAT,
    1493              :                     error.Format());
    1494            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1495              : 
    1496            0 :     CommissioningDelegate::CommissioningReport report;
    1497            0 :     report.Set<AttestationErrorInfo>(commissioner->mAttestationResult);
    1498            0 :     commissioner->CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
    1499            0 : }
    1500              : 
    1501            0 : void DeviceCommissioner::OnICDManagementRegisterClientResponse(
    1502              :     void * context, const app::Clusters::IcdManagement::Commands::RegisterClientResponse::DecodableType & data)
    1503              : {
    1504            0 :     CHIP_ERROR err                    = CHIP_NO_ERROR;
    1505            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1506            0 :     VerifyOrExit(commissioner != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
    1507            0 :     VerifyOrExit(commissioner->mCommissioningStage == CommissioningStage::kICDRegistration, err = CHIP_ERROR_INCORRECT_STATE);
    1508            0 :     VerifyOrExit(commissioner->mDeviceBeingCommissioned != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
    1509              : 
    1510            0 :     if (commissioner->mPairingDelegate != nullptr)
    1511              :     {
    1512            0 :         commissioner->mPairingDelegate->OnICDRegistrationComplete(
    1513            0 :             ScopedNodeId(commissioner->mDeviceBeingCommissioned->GetDeviceId(), commissioner->GetFabricIndex()), data.ICDCounter);
    1514              :     }
    1515              : 
    1516            0 : exit:
    1517            0 :     CommissioningDelegate::CommissioningReport report;
    1518            0 :     commissioner->CommissioningStageComplete(err, report);
    1519            0 : }
    1520              : 
    1521            0 : void DeviceCommissioner::OnICDManagementStayActiveResponse(
    1522              :     void * context, const app::Clusters::IcdManagement::Commands::StayActiveResponse::DecodableType & data)
    1523              : {
    1524            0 :     CHIP_ERROR err                    = CHIP_NO_ERROR;
    1525            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1526            0 :     VerifyOrExit(commissioner != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
    1527            0 :     VerifyOrExit(commissioner->mCommissioningStage == CommissioningStage::kICDSendStayActive, err = CHIP_ERROR_INCORRECT_STATE);
    1528            0 :     VerifyOrExit(commissioner->mDeviceBeingCommissioned != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
    1529              : 
    1530            0 :     if (commissioner->mPairingDelegate != nullptr)
    1531              :     {
    1532            0 :         commissioner->mPairingDelegate->OnICDStayActiveComplete(
    1533              : 
    1534            0 :             ScopedNodeId(commissioner->mDeviceBeingCommissioned->GetDeviceId(), commissioner->GetFabricIndex()),
    1535            0 :             data.promisedActiveDuration);
    1536              :     }
    1537              : 
    1538            0 : exit:
    1539            0 :     CommissioningDelegate::CommissioningReport report;
    1540            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    1541            0 : }
    1542              : 
    1543            0 : bool DeviceCommissioner::ExtendArmFailSafeInternal(DeviceProxy * proxy, CommissioningStage step, uint16_t armFailSafeTimeout,
    1544              :                                                    Optional<System::Clock::Timeout> commandTimeout,
    1545              :                                                    OnExtendFailsafeSuccess onSuccess, OnExtendFailsafeFailure onFailure,
    1546              :                                                    bool fireAndForget)
    1547              : {
    1548              :     using namespace System;
    1549              :     using namespace System::Clock;
    1550            0 :     auto now                = SystemClock().GetMonotonicTimestamp();
    1551            0 :     auto newFailSafeTimeout = now + Seconds16(armFailSafeTimeout);
    1552            0 :     if (newFailSafeTimeout < proxy->GetFailSafeExpirationTimestamp())
    1553              :     {
    1554            0 :         ChipLogProgress(
    1555              :             Controller, "Skipping arming failsafe: new time (%u seconds from now) before old time (%u seconds from now)",
    1556              :             armFailSafeTimeout, std::chrono::duration_cast<Seconds16>(proxy->GetFailSafeExpirationTimestamp() - now).count());
    1557            0 :         return false;
    1558              :     }
    1559              : 
    1560            0 :     uint64_t breadcrumb = static_cast<uint64_t>(step);
    1561            0 :     GeneralCommissioning::Commands::ArmFailSafe::Type request;
    1562            0 :     request.expiryLengthSeconds = armFailSafeTimeout;
    1563            0 :     request.breadcrumb          = breadcrumb;
    1564            0 :     ChipLogProgress(Controller, "Arming failsafe (%u seconds)", request.expiryLengthSeconds);
    1565            0 :     CHIP_ERROR err = SendCommissioningCommand(proxy, request, onSuccess, onFailure, kRootEndpointId, commandTimeout, fireAndForget);
    1566            0 :     if (err != CHIP_NO_ERROR)
    1567              :     {
    1568            0 :         onFailure((!fireAndForget) ? this : nullptr, err);
    1569            0 :         return true; // we have called onFailure already
    1570              :     }
    1571              : 
    1572              :     // Note: The stored timestamp may become invalid if we fail asynchronously
    1573            0 :     proxy->SetFailSafeExpirationTimestamp(newFailSafeTimeout);
    1574            0 :     return true;
    1575              : }
    1576              : 
    1577            0 : void DeviceCommissioner::ExtendArmFailSafeForDeviceAttestation(const Credentials::DeviceAttestationVerifier::AttestationInfo & info,
    1578              :                                                                Credentials::AttestationVerificationResult result)
    1579              : {
    1580            0 :     mAttestationResult = result;
    1581              : 
    1582            0 :     auto & params                                                      = mDefaultCommissioner->GetCommissioningParameters();
    1583            0 :     Credentials::DeviceAttestationDelegate * deviceAttestationDelegate = params.GetDeviceAttestationDelegate();
    1584              : 
    1585            0 :     mAttestationDeviceInfo = Platform::MakeUnique<Credentials::DeviceAttestationVerifier::AttestationDeviceInfo>(info);
    1586              : 
    1587            0 :     auto expiryLengthSeconds      = deviceAttestationDelegate->FailSafeExpiryTimeoutSecs();
    1588            0 :     bool waitForFailsafeExtension = expiryLengthSeconds.HasValue();
    1589            0 :     if (waitForFailsafeExtension)
    1590              :     {
    1591            0 :         ChipLogProgress(Controller, "Changing fail-safe timer to %u seconds to handle DA failure", expiryLengthSeconds.Value());
    1592              :         // Per spec, anything we do with the fail-safe armed must not time out
    1593              :         // in less than kMinimumCommissioningStepTimeout.
    1594              :         waitForFailsafeExtension =
    1595            0 :             ExtendArmFailSafeInternal(mDeviceBeingCommissioned, mCommissioningStage, expiryLengthSeconds.Value(),
    1596            0 :                                       MakeOptional(kMinimumCommissioningStepTimeout), OnArmFailSafeExtendedForDeviceAttestation,
    1597              :                                       OnFailedToExtendedArmFailSafeDeviceAttestation, /* fireAndForget = */ false);
    1598              :     }
    1599              :     else
    1600              :     {
    1601            0 :         ChipLogProgress(Controller, "Proceeding without changing fail-safe timer value as delegate has not set it");
    1602              :     }
    1603              : 
    1604            0 :     if (!waitForFailsafeExtension)
    1605              :     {
    1606            0 :         HandleDeviceAttestationCompleted();
    1607              :     }
    1608            0 : }
    1609              : 
    1610            0 : CHIP_ERROR DeviceCommissioner::ValidateAttestationInfo(const Credentials::DeviceAttestationVerifier::AttestationInfo & info)
    1611              : {
    1612              :     MATTER_TRACE_SCOPE("ValidateAttestationInfo", "DeviceCommissioner");
    1613            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1614            0 :     VerifyOrReturnError(mDeviceAttestationVerifier != nullptr, CHIP_ERROR_INCORRECT_STATE);
    1615              : 
    1616            0 :     mDeviceAttestationVerifier->VerifyAttestationInformation(info, &mDeviceAttestationInformationVerificationCallback);
    1617              : 
    1618              :     // TODO: Validate Firmware Information
    1619              : 
    1620            0 :     return CHIP_NO_ERROR;
    1621              : }
    1622              : 
    1623              : CHIP_ERROR
    1624            0 : DeviceCommissioner::CheckForRevokedDACChain(const Credentials::DeviceAttestationVerifier::AttestationInfo & info)
    1625              : {
    1626              :     MATTER_TRACE_SCOPE("CheckForRevokedDACChain", "DeviceCommissioner");
    1627            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1628            0 :     VerifyOrReturnError(mDeviceAttestationVerifier != nullptr, CHIP_ERROR_INCORRECT_STATE);
    1629              : 
    1630            0 :     mDeviceAttestationVerifier->CheckForRevokedDACChain(info, &mDeviceAttestationInformationVerificationCallback);
    1631              : 
    1632            0 :     return CHIP_NO_ERROR;
    1633              : }
    1634              : 
    1635            0 : CHIP_ERROR DeviceCommissioner::ValidateCSR(DeviceProxy * proxy, const ByteSpan & NOCSRElements,
    1636              :                                            const ByteSpan & AttestationSignature, const ByteSpan & dac, const ByteSpan & csrNonce)
    1637              : {
    1638              :     MATTER_TRACE_SCOPE("ValidateCSR", "DeviceCommissioner");
    1639            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1640            0 :     VerifyOrReturnError(mDeviceAttestationVerifier != nullptr, CHIP_ERROR_INCORRECT_STATE);
    1641              : 
    1642            0 :     P256PublicKey dacPubkey;
    1643            0 :     ReturnErrorOnFailure(ExtractPubkeyFromX509Cert(dac, dacPubkey));
    1644              : 
    1645              :     // Retrieve attestation challenge
    1646              :     ByteSpan attestationChallenge =
    1647            0 :         proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge();
    1648              : 
    1649              :     // The operational CA should also verify this on its end during NOC generation, if end-to-end attestation is desired.
    1650            0 :     return mDeviceAttestationVerifier->VerifyNodeOperationalCSRInformation(NOCSRElements, attestationChallenge,
    1651            0 :                                                                            AttestationSignature, dacPubkey, csrNonce);
    1652            0 : }
    1653              : 
    1654            0 : CHIP_ERROR DeviceCommissioner::SendOperationalCertificateSigningRequestCommand(DeviceProxy * device, const ByteSpan & csrNonce,
    1655              :                                                                                Optional<System::Clock::Timeout> timeout)
    1656              : {
    1657              :     MATTER_TRACE_SCOPE("SendOperationalCertificateSigningRequestCommand", "DeviceCommissioner");
    1658            0 :     ChipLogDetail(Controller, "Sending CSR request to %p device", device);
    1659            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1660              : 
    1661            0 :     OperationalCredentials::Commands::CSRRequest::Type request;
    1662            0 :     request.CSRNonce = csrNonce;
    1663              : 
    1664            0 :     ReturnErrorOnFailure(SendCommissioningCommand(device, request, OnOperationalCertificateSigningRequest, OnCSRFailureResponse,
    1665              :                                                   kRootEndpointId, timeout));
    1666            0 :     ChipLogDetail(Controller, "Sent CSR request, waiting for the CSR");
    1667            0 :     return CHIP_NO_ERROR;
    1668              : }
    1669              : 
    1670            0 : void DeviceCommissioner::OnCSRFailureResponse(void * context, CHIP_ERROR error)
    1671              : {
    1672              :     MATTER_TRACE_SCOPE("OnCSRFailureResponse", "DeviceCommissioner");
    1673            0 :     ChipLogProgress(Controller, "Device failed to receive the CSR request Response: %" CHIP_ERROR_FORMAT, error.Format());
    1674            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1675            0 :     commissioner->CommissioningStageComplete(error);
    1676            0 : }
    1677              : 
    1678            0 : void DeviceCommissioner::OnOperationalCertificateSigningRequest(
    1679              :     void * context, const OperationalCredentials::Commands::CSRResponse::DecodableType & data)
    1680              : {
    1681              :     MATTER_TRACE_SCOPE("OnOperationalCertificateSigningRequest", "DeviceCommissioner");
    1682            0 :     ChipLogProgress(Controller, "Received certificate signing request from the device");
    1683            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1684              : 
    1685            0 :     CommissioningDelegate::CommissioningReport report;
    1686            0 :     report.Set<CSRResponse>(CSRResponse(data.NOCSRElements, data.attestationSignature));
    1687            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    1688            0 : }
    1689              : 
    1690            0 : void DeviceCommissioner::OnDeviceNOCChainGeneration(void * context, CHIP_ERROR status, const ByteSpan & noc, const ByteSpan & icac,
    1691              :                                                     const ByteSpan & rcac, Optional<IdentityProtectionKeySpan> ipk,
    1692              :                                                     Optional<NodeId> adminSubject)
    1693              : {
    1694              :     MATTER_TRACE_SCOPE("OnDeviceNOCChainGeneration", "DeviceCommissioner");
    1695            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1696              : 
    1697              :     // The placeholder IPK is not satisfactory, but is there to fill the NocChain struct on error. It will still fail.
    1698            0 :     const uint8_t placeHolderIpk[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1699              :                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    1700            0 :     if (status == CHIP_NO_ERROR && !ipk.HasValue())
    1701              :     {
    1702            0 :         ChipLogError(Controller, "Did not have an IPK from the OperationalCredentialsIssuer! Cannot commission.");
    1703            0 :         status = CHIP_ERROR_INVALID_ARGUMENT;
    1704              :     }
    1705              : 
    1706            0 :     ChipLogProgress(Controller, "Received callback from the CA for NOC Chain generation. Status: %" CHIP_ERROR_FORMAT,
    1707              :                     status.Format());
    1708            0 :     if (status == CHIP_NO_ERROR && commissioner->mState != State::Initialized)
    1709              :     {
    1710            0 :         status = CHIP_ERROR_INCORRECT_STATE;
    1711              :     }
    1712            0 :     if (status != CHIP_NO_ERROR)
    1713              :     {
    1714            0 :         ChipLogError(Controller, "Failed in generating device's operational credentials. Error: %" CHIP_ERROR_FORMAT,
    1715              :                      status.Format());
    1716              :     }
    1717              : 
    1718              :     // TODO - Verify that the generated root cert matches with commissioner's root cert
    1719            0 :     CommissioningDelegate::CommissioningReport report;
    1720            0 :     report.Set<NocChain>(NocChain(noc, icac, rcac, ipk.HasValue() ? ipk.Value() : IdentityProtectionKeySpan(placeHolderIpk),
    1721            0 :                                   adminSubject.HasValue() ? adminSubject.Value() : commissioner->GetNodeId()));
    1722            0 :     commissioner->CommissioningStageComplete(status, report);
    1723            0 : }
    1724              : 
    1725            0 : CHIP_ERROR DeviceCommissioner::IssueNOCChain(const ByteSpan & NOCSRElements, NodeId nodeId,
    1726              :                                              chip::Callback::Callback<OnNOCChainGeneration> * callback)
    1727              : {
    1728              :     MATTER_TRACE_SCOPE("IssueNOCChain", "DeviceCommissioner");
    1729            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1730              : 
    1731            0 :     ChipLogProgress(Controller, "Getting certificate chain for the device on fabric idx %u", static_cast<unsigned>(mFabricIndex));
    1732              : 
    1733            0 :     mOperationalCredentialsDelegate->SetNodeIdForNextNOCRequest(nodeId);
    1734              : 
    1735            0 :     if (mFabricIndex != kUndefinedFabricIndex)
    1736              :     {
    1737            0 :         mOperationalCredentialsDelegate->SetFabricIdForNextNOCRequest(GetFabricId());
    1738              :     }
    1739              : 
    1740              :     // Note: we don't have attestationSignature, attestationChallenge, DAC, PAI so we are just providing an empty ByteSpan
    1741              :     // for those arguments.
    1742            0 :     return mOperationalCredentialsDelegate->GenerateNOCChain(NOCSRElements, ByteSpan(), ByteSpan(), ByteSpan(), ByteSpan(),
    1743            0 :                                                              ByteSpan(), callback);
    1744              : }
    1745              : 
    1746            0 : CHIP_ERROR DeviceCommissioner::ProcessCSR(DeviceProxy * proxy, const ByteSpan & NOCSRElements,
    1747              :                                           const ByteSpan & AttestationSignature, const ByteSpan & dac, const ByteSpan & pai,
    1748              :                                           const ByteSpan & csrNonce)
    1749              : {
    1750              :     MATTER_TRACE_SCOPE("ProcessOpCSR", "DeviceCommissioner");
    1751            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1752              : 
    1753            0 :     ChipLogProgress(Controller, "Getting certificate chain for the device from the issuer");
    1754              : 
    1755            0 :     P256PublicKey dacPubkey;
    1756            0 :     ReturnErrorOnFailure(ExtractPubkeyFromX509Cert(dac, dacPubkey));
    1757              : 
    1758              :     // Retrieve attestation challenge
    1759              :     ByteSpan attestationChallenge =
    1760            0 :         proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge();
    1761              : 
    1762            0 :     mOperationalCredentialsDelegate->SetNodeIdForNextNOCRequest(proxy->GetDeviceId());
    1763              : 
    1764            0 :     if (mFabricIndex != kUndefinedFabricIndex)
    1765              :     {
    1766            0 :         mOperationalCredentialsDelegate->SetFabricIdForNextNOCRequest(GetFabricId());
    1767              :     }
    1768              : 
    1769            0 :     return mOperationalCredentialsDelegate->GenerateNOCChain(NOCSRElements, csrNonce, AttestationSignature, attestationChallenge,
    1770            0 :                                                              dac, pai, &mDeviceNOCChainCallback);
    1771            0 : }
    1772              : 
    1773            0 : CHIP_ERROR DeviceCommissioner::SendOperationalCertificate(DeviceProxy * device, const ByteSpan & nocCertBuf,
    1774              :                                                           const Optional<ByteSpan> & icaCertBuf,
    1775              :                                                           const IdentityProtectionKeySpan ipk, const NodeId adminSubject,
    1776              :                                                           Optional<System::Clock::Timeout> timeout)
    1777              : {
    1778              :     MATTER_TRACE_SCOPE("SendOperationalCertificate", "DeviceCommissioner");
    1779              : 
    1780            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1781              : 
    1782            0 :     OperationalCredentials::Commands::AddNOC::Type request;
    1783            0 :     request.NOCValue         = nocCertBuf;
    1784            0 :     request.ICACValue        = icaCertBuf;
    1785            0 :     request.IPKValue         = ipk;
    1786            0 :     request.caseAdminSubject = adminSubject;
    1787            0 :     request.adminVendorId    = mVendorId;
    1788              : 
    1789            0 :     ReturnErrorOnFailure(SendCommissioningCommand(device, request, OnOperationalCertificateAddResponse, OnAddNOCFailureResponse,
    1790              :                                                   kRootEndpointId, timeout));
    1791              : 
    1792            0 :     ChipLogProgress(Controller, "Sent operational certificate to the device");
    1793              : 
    1794            0 :     return CHIP_NO_ERROR;
    1795              : }
    1796              : 
    1797            0 : CHIP_ERROR DeviceCommissioner::ConvertFromOperationalCertStatus(OperationalCredentials::NodeOperationalCertStatusEnum err)
    1798              : {
    1799              :     using OperationalCredentials::NodeOperationalCertStatusEnum;
    1800            0 :     switch (err)
    1801              :     {
    1802            0 :     case NodeOperationalCertStatusEnum::kOk:
    1803            0 :         return CHIP_NO_ERROR;
    1804            0 :     case NodeOperationalCertStatusEnum::kInvalidPublicKey:
    1805            0 :         return CHIP_ERROR_INVALID_PUBLIC_KEY;
    1806            0 :     case NodeOperationalCertStatusEnum::kInvalidNodeOpId:
    1807            0 :         return CHIP_ERROR_WRONG_NODE_ID;
    1808            0 :     case NodeOperationalCertStatusEnum::kInvalidNOC:
    1809            0 :         return CHIP_ERROR_UNSUPPORTED_CERT_FORMAT;
    1810            0 :     case NodeOperationalCertStatusEnum::kMissingCsr:
    1811            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1812            0 :     case NodeOperationalCertStatusEnum::kTableFull:
    1813            0 :         return CHIP_ERROR_NO_MEMORY;
    1814            0 :     case NodeOperationalCertStatusEnum::kInvalidAdminSubject:
    1815            0 :         return CHIP_ERROR_INVALID_ADMIN_SUBJECT;
    1816            0 :     case NodeOperationalCertStatusEnum::kFabricConflict:
    1817            0 :         return CHIP_ERROR_FABRIC_EXISTS;
    1818            0 :     case NodeOperationalCertStatusEnum::kLabelConflict:
    1819            0 :         return CHIP_ERROR_INVALID_ARGUMENT;
    1820            0 :     case NodeOperationalCertStatusEnum::kInvalidFabricIndex:
    1821            0 :         return CHIP_ERROR_INVALID_FABRIC_INDEX;
    1822            0 :     case NodeOperationalCertStatusEnum::kUnknownEnumValue:
    1823              :         // Is this a reasonable value?
    1824            0 :         return CHIP_ERROR_CERT_LOAD_FAILED;
    1825              :     }
    1826              : 
    1827            0 :     return CHIP_ERROR_CERT_LOAD_FAILED;
    1828              : }
    1829              : 
    1830            0 : void DeviceCommissioner::OnAddNOCFailureResponse(void * context, CHIP_ERROR error)
    1831              : {
    1832              :     MATTER_TRACE_SCOPE("OnAddNOCFailureResponse", "DeviceCommissioner");
    1833            0 :     ChipLogProgress(Controller, "Device failed to receive the operational certificate Response: %" CHIP_ERROR_FORMAT,
    1834              :                     error.Format());
    1835            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1836            0 :     commissioner->CommissioningStageComplete(error);
    1837            0 : }
    1838              : 
    1839            0 : void DeviceCommissioner::OnOperationalCertificateAddResponse(
    1840              :     void * context, const OperationalCredentials::Commands::NOCResponse::DecodableType & data)
    1841              : {
    1842              :     MATTER_TRACE_SCOPE("OnOperationalCertificateAddResponse", "DeviceCommissioner");
    1843            0 :     ChipLogProgress(Controller, "Device returned status %d on receiving the NOC", to_underlying(data.statusCode));
    1844            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1845              : 
    1846            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    1847              : 
    1848            0 :     VerifyOrExit(commissioner->mState == State::Initialized, err = CHIP_ERROR_INCORRECT_STATE);
    1849              : 
    1850            0 :     VerifyOrExit(commissioner->mDeviceBeingCommissioned != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
    1851              : 
    1852            0 :     err = ConvertFromOperationalCertStatus(data.statusCode);
    1853            0 :     SuccessOrExit(err);
    1854              : 
    1855            0 :     err = commissioner->OnOperationalCredentialsProvisioningCompletion(commissioner->mDeviceBeingCommissioned);
    1856              : 
    1857            0 : exit:
    1858            0 :     if (err != CHIP_NO_ERROR)
    1859              :     {
    1860            0 :         ChipLogProgress(Controller, "Add NOC failed with error: %" CHIP_ERROR_FORMAT, err.Format());
    1861            0 :         commissioner->CommissioningStageComplete(err);
    1862              :     }
    1863            0 : }
    1864              : 
    1865            0 : CHIP_ERROR DeviceCommissioner::SendTrustedRootCertificate(DeviceProxy * device, const ByteSpan & rcac,
    1866              :                                                           Optional<System::Clock::Timeout> timeout)
    1867              : {
    1868              :     MATTER_TRACE_SCOPE("SendTrustedRootCertificate", "DeviceCommissioner");
    1869            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1870              : 
    1871            0 :     ChipLogProgress(Controller, "Sending root certificate to the device");
    1872              : 
    1873            0 :     OperationalCredentials::Commands::AddTrustedRootCertificate::Type request;
    1874            0 :     request.rootCACertificate = rcac;
    1875            0 :     ReturnErrorOnFailure(
    1876              :         SendCommissioningCommand(device, request, OnRootCertSuccessResponse, OnRootCertFailureResponse, kRootEndpointId, timeout));
    1877              : 
    1878            0 :     ChipLogProgress(Controller, "Sent root certificate to the device");
    1879              : 
    1880            0 :     return CHIP_NO_ERROR;
    1881              : }
    1882              : 
    1883            0 : void DeviceCommissioner::OnRootCertSuccessResponse(void * context, const chip::app::DataModel::NullObjectType &)
    1884              : {
    1885              :     MATTER_TRACE_SCOPE("OnRootCertSuccessResponse", "DeviceCommissioner");
    1886            0 :     ChipLogProgress(Controller, "Device confirmed that it has received the root certificate");
    1887            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1888            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    1889            0 : }
    1890              : 
    1891            0 : void DeviceCommissioner::OnRootCertFailureResponse(void * context, CHIP_ERROR error)
    1892              : {
    1893              :     MATTER_TRACE_SCOPE("OnRootCertFailureResponse", "DeviceCommissioner");
    1894            0 :     ChipLogProgress(Controller, "Device failed to receive the root certificate Response: %" CHIP_ERROR_FORMAT, error.Format());
    1895            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1896            0 :     commissioner->CommissioningStageComplete(error);
    1897            0 : }
    1898              : 
    1899            0 : CHIP_ERROR DeviceCommissioner::OnOperationalCredentialsProvisioningCompletion(DeviceProxy * device)
    1900              : {
    1901              :     MATTER_TRACE_SCOPE("OnOperationalCredentialsProvisioningCompletion", "DeviceCommissioner");
    1902            0 :     ChipLogProgress(Controller, "Operational credentials provisioned on device %p", device);
    1903            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1904              : 
    1905            0 :     if (mPairingDelegate != nullptr)
    1906              :     {
    1907            0 :         mPairingDelegate->OnStatusUpdate(DevicePairingDelegate::SecurePairingSuccess);
    1908              :     }
    1909            0 :     CommissioningStageComplete(CHIP_NO_ERROR);
    1910              : 
    1911            0 :     return CHIP_NO_ERROR;
    1912              : }
    1913              : 
    1914              : #if CONFIG_NETWORK_LAYER_BLE
    1915              : #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
    1916              : void DeviceCommissioner::ConnectBleTransportToSelf()
    1917              : {
    1918              :     Transport::BLEBase & transport = std::get<Transport::BLE<1>>(mSystemState->TransportMgr()->GetTransport().GetTransports());
    1919              :     if (!transport.IsBleLayerTransportSetToSelf())
    1920              :     {
    1921              :         transport.SetBleLayerTransportToSelf();
    1922              :     }
    1923              : }
    1924              : #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
    1925              : 
    1926            0 : void DeviceCommissioner::CloseBleConnection()
    1927              : {
    1928              :     // It is fine since we can only commission one device at the same time.
    1929              :     // We should be able to distinguish different BLE connections if we want
    1930              :     // to commission multiple devices at the same time over BLE.
    1931            0 :     mSystemState->BleLayer()->CloseAllBleConnections();
    1932            0 : }
    1933              : #endif
    1934              : 
    1935            0 : CHIP_ERROR DeviceCommissioner::DiscoverCommissionableNodes(Dnssd::DiscoveryFilter filter)
    1936              : {
    1937            0 :     ReturnErrorOnFailure(SetUpNodeDiscovery());
    1938            0 :     return mDNSResolver.DiscoverCommissionableNodes(filter);
    1939              : }
    1940              : 
    1941            2 : CHIP_ERROR DeviceCommissioner::StopCommissionableDiscovery()
    1942              : {
    1943            2 :     return mDNSResolver.StopDiscovery();
    1944              : }
    1945              : 
    1946            0 : const Dnssd::CommissionNodeData * DeviceCommissioner::GetDiscoveredDevice(int idx)
    1947              : {
    1948            0 :     return GetDiscoveredNode(idx);
    1949              : }
    1950              : 
    1951              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
    1952              : 
    1953              : CHIP_ERROR DeviceCommissioner::SetUdcListenPort(uint16_t listenPort)
    1954              : {
    1955              :     if (mState == State::Initialized)
    1956              :     {
    1957              :         return CHIP_ERROR_INCORRECT_STATE;
    1958              :     }
    1959              : 
    1960              :     mUdcListenPort = listenPort;
    1961              :     return CHIP_NO_ERROR;
    1962              : }
    1963              : 
    1964              : void DeviceCommissioner::FindCommissionableNode(char * instanceName)
    1965              : {
    1966              :     Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kInstanceName, instanceName);
    1967              :     TEMPORARY_RETURN_IGNORED DiscoverCommissionableNodes(filter);
    1968              : }
    1969              : 
    1970              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
    1971              : 
    1972            0 : void DeviceCommissioner::OnNodeDiscovered(const chip::Dnssd::DiscoveredNodeData & nodeData)
    1973              : {
    1974              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
    1975              :     if (mUdcServer != nullptr)
    1976              :     {
    1977              :         mUdcServer->OnCommissionableNodeFound(nodeData);
    1978              :     }
    1979              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
    1980            0 :     if (nodeData.Get<Dnssd::CommissionNodeData>().threadMeshcop)
    1981              :     {
    1982            0 :         mAutoCommissioner.SetNetworkSetupNeeded(true);
    1983              :     }
    1984            0 :     AbstractDnssdDiscoveryController::OnNodeDiscovered(nodeData);
    1985            0 :     mSetUpCodePairer.NotifyCommissionableDeviceDiscovered(nodeData);
    1986            0 : }
    1987              : 
    1988            0 : void DeviceCommissioner::OnBasicSuccess(void * context, const chip::app::DataModel::NullObjectType &)
    1989              : {
    1990            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1991            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    1992            0 : }
    1993              : 
    1994            0 : void DeviceCommissioner::OnBasicFailure(void * context, CHIP_ERROR error)
    1995              : {
    1996            0 :     ChipLogProgress(Controller, "Received failure response: %" CHIP_ERROR_FORMAT, error.Format());
    1997            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1998            0 :     commissioner->CommissioningStageComplete(error);
    1999            0 : }
    2000              : 
    2001            0 : static GeneralCommissioning::Commands::ArmFailSafe::Type DisarmFailsafeRequest()
    2002              : {
    2003            0 :     GeneralCommissioning::Commands::ArmFailSafe::Type request;
    2004            0 :     request.expiryLengthSeconds = 0; // Expire immediately.
    2005            0 :     request.breadcrumb          = 0;
    2006            0 :     return request;
    2007              : }
    2008              : 
    2009            0 : static void MarkForEviction(const Optional<SessionHandle> & session)
    2010              : {
    2011            0 :     if (session.HasValue())
    2012              :     {
    2013            0 :         session.Value()->AsSecureSession()->MarkForEviction();
    2014              :     }
    2015            0 : }
    2016              : 
    2017            0 : void DeviceCommissioner::CleanupCommissioning(DeviceProxy * proxy, NodeId nodeId, const CompletionStatus & completionStatus)
    2018              : {
    2019              :     // At this point, proxy == mDeviceBeingCommissioned, nodeId == mDeviceBeingCommissioned->GetDeviceId()
    2020              : 
    2021            0 :     mCommissioningCompletionStatus = completionStatus;
    2022              : 
    2023            0 :     if (completionStatus.err == CHIP_NO_ERROR)
    2024              :     {
    2025              :         // CommissioningStageComplete uses mDeviceBeingCommissioned, which can
    2026              :         // be commissionee if we are cleaning up before we've gone operational.  Normally
    2027              :         // that would not happen in this non-error case, _except_ if we were told to skip sending
    2028              :         // CommissioningComplete: in that case we do not have an operational DeviceProxy, so
    2029              :         // we're using our CommissioneeDeviceProxy to do a successful cleanup.
    2030              :         //
    2031              :         // This means we have to call CommissioningStageComplete() before we destroy commissionee.
    2032              :         //
    2033              :         // This should be safe, because CommissioningStageComplete() does not call CleanupCommissioning
    2034              :         // when called in the cleanup stage (which is where we are), and StopPairing does not directly release
    2035              :         // mDeviceBeingCommissioned.
    2036            0 :         CommissioningStageComplete(CHIP_NO_ERROR);
    2037              : 
    2038            0 :         CommissioneeDeviceProxy * commissionee = FindCommissioneeDevice(nodeId);
    2039            0 :         if (commissionee != nullptr)
    2040              :         {
    2041            0 :             ReleaseCommissioneeDevice(commissionee);
    2042              :         }
    2043              :         // Send the callbacks, we're done.
    2044            0 :         SendCommissioningCompleteCallbacks(nodeId, mCommissioningCompletionStatus);
    2045              :     }
    2046            0 :     else if (completionStatus.err == CHIP_ERROR_CANCELLED)
    2047              :     {
    2048              :         // If we're cleaning up because cancellation has been requested via StopPairing(), expire the failsafe
    2049              :         // in the background and reset our state synchronously, so a new commissioning attempt can be started.
    2050            0 :         CommissioneeDeviceProxy * commissionee = FindCommissioneeDevice(nodeId);
    2051            0 :         SessionHolder session((commissionee == proxy) ? commissionee->DetachSecureSession().Value()
    2052            0 :                                                       : proxy->GetSecureSession().Value());
    2053              : 
    2054            0 :         auto request     = DisarmFailsafeRequest();
    2055            0 :         auto onSuccessCb = [session](const app::ConcreteCommandPath & aPath, const app::StatusIB & aStatus,
    2056              :                                      const decltype(request)::ResponseType & responseData) {
    2057            0 :             ChipLogProgress(Controller, "Failsafe disarmed");
    2058            0 :             MarkForEviction(session.Get());
    2059            0 :         };
    2060            0 :         auto onFailureCb = [session](CHIP_ERROR aError) {
    2061            0 :             ChipLogProgress(Controller, "Ignoring failure to disarm failsafe: %" CHIP_ERROR_FORMAT, aError.Format());
    2062            0 :             MarkForEviction(session.Get());
    2063            0 :         };
    2064              : 
    2065            0 :         ChipLogProgress(Controller, "Disarming failsafe on device %p in background", proxy);
    2066            0 :         CHIP_ERROR err = InvokeCommandRequest(proxy->GetExchangeManager(), session.Get().Value(), kRootEndpointId, request,
    2067              :                                               onSuccessCb, onFailureCb);
    2068            0 :         if (err != CHIP_NO_ERROR)
    2069              :         {
    2070            0 :             ChipLogError(Controller, "Failed to send command to disarm fail-safe: %" CHIP_ERROR_FORMAT, err.Format());
    2071              :         }
    2072              : 
    2073            0 :         CleanupDoneAfterError();
    2074            0 :     }
    2075            0 :     else if (completionStatus.failedStage.HasValue() && completionStatus.failedStage.Value() >= kWiFiNetworkSetup)
    2076              :     {
    2077              :         // If we were already doing network setup, we need to retain the pase session and start again from network setup stage.
    2078              :         // We do not need to reset the failsafe here because we want to keep everything on the device up to this point, so just
    2079              :         // send the completion callbacks (see "Commissioning Flows Error Handling" in the spec).
    2080            0 :         CommissioningStageComplete(CHIP_NO_ERROR);
    2081            0 :         SendCommissioningCompleteCallbacks(nodeId, mCommissioningCompletionStatus);
    2082              :     }
    2083              :     else
    2084              :     {
    2085              :         // If we've failed somewhere in the early stages (or we don't have a failedStage specified), we need to start from the
    2086              :         // beginning. However, because some of the commands can only be sent once per arm-failsafe, we also need to force a reset on
    2087              :         // the failsafe so we can start fresh on the next attempt.
    2088            0 :         ChipLogProgress(Controller, "Disarming failsafe on device %p", proxy);
    2089            0 :         auto request   = DisarmFailsafeRequest();
    2090            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnDisarmFailsafe, OnDisarmFailsafeFailure, kRootEndpointId);
    2091            0 :         if (err != CHIP_NO_ERROR)
    2092              :         {
    2093              :             // We won't get any async callbacks here, so just pretend like the command errored out async.
    2094            0 :             ChipLogError(Controller, "Failed to send command to disarm fail-safe: %" CHIP_ERROR_FORMAT, err.Format());
    2095            0 :             CleanupDoneAfterError();
    2096              :         }
    2097              :     }
    2098            0 : }
    2099              : 
    2100            0 : void DeviceCommissioner::OnDisarmFailsafe(void * context,
    2101              :                                           const GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType & data)
    2102              : {
    2103            0 :     ChipLogProgress(Controller, "Failsafe disarmed");
    2104            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2105            0 :     commissioner->CleanupDoneAfterError();
    2106            0 : }
    2107              : 
    2108            0 : void DeviceCommissioner::OnDisarmFailsafeFailure(void * context, CHIP_ERROR error)
    2109              : {
    2110            0 :     ChipLogProgress(Controller, "Ignoring failure to disarm failsafe: %" CHIP_ERROR_FORMAT, error.Format());
    2111            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2112            0 :     commissioner->CleanupDoneAfterError();
    2113            0 : }
    2114              : 
    2115            0 : void DeviceCommissioner::CleanupDoneAfterError()
    2116              : {
    2117              :     // If someone nulled out our mDeviceBeingCommissioned, there's nothing else
    2118              :     // to do here.
    2119            0 :     VerifyOrReturn(mDeviceBeingCommissioned != nullptr);
    2120              : 
    2121            0 :     NodeId nodeId = mDeviceBeingCommissioned->GetDeviceId();
    2122              : 
    2123              :     // Signal completion - this will reset mDeviceBeingCommissioned.
    2124            0 :     CommissioningStageComplete(CHIP_NO_ERROR);
    2125              : 
    2126              :     // At this point, we also want to close off the pase session so we need to re-establish
    2127            0 :     CommissioneeDeviceProxy * commissionee = FindCommissioneeDevice(nodeId);
    2128              : 
    2129              :     // If we've disarmed the failsafe, it's because we're starting again, so kill the pase connection.
    2130            0 :     if (commissionee != nullptr)
    2131              :     {
    2132            0 :         ReleaseCommissioneeDevice(commissionee);
    2133              :     }
    2134              : 
    2135              :     // Invoke callbacks last, after we have cleared up all state.
    2136            0 :     SendCommissioningCompleteCallbacks(nodeId, mCommissioningCompletionStatus);
    2137              : }
    2138              : 
    2139            0 : void DeviceCommissioner::SendCommissioningCompleteCallbacks(NodeId nodeId, const CompletionStatus & completionStatus)
    2140              : {
    2141              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissionerCommission, completionStatus.err);
    2142              : 
    2143            0 :     ChipLogProgress(Controller, "Commissioning complete for node ID 0x" ChipLogFormatX64 ": %s", ChipLogValueX64(nodeId),
    2144              :                     (completionStatus.err == CHIP_NO_ERROR ? "success" : completionStatus.err.AsString()));
    2145            0 :     mCommissioningStage = CommissioningStage::kSecurePairing;
    2146              : 
    2147            0 :     if (mPairingDelegate == nullptr)
    2148              :     {
    2149            0 :         return;
    2150              :     }
    2151              : 
    2152            0 :     mPairingDelegate->OnCommissioningComplete(nodeId, completionStatus.err);
    2153              : 
    2154            0 :     PeerId peerId(GetCompressedFabricId(), nodeId);
    2155            0 :     if (completionStatus.err == CHIP_NO_ERROR)
    2156              :     {
    2157            0 :         mPairingDelegate->OnCommissioningSuccess(peerId);
    2158              :     }
    2159              :     else
    2160              :     {
    2161              :         // TODO: We should propogate detailed error information (commissioningError, networkCommissioningStatus) from
    2162              :         // completionStatus.
    2163            0 :         mPairingDelegate->OnCommissioningFailure(peerId, completionStatus.err, completionStatus.failedStage.ValueOr(kError),
    2164            0 :                                                  completionStatus.attestationResult);
    2165              :     }
    2166              : }
    2167              : 
    2168            0 : void DeviceCommissioner::CommissioningStageComplete(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report)
    2169              : {
    2170              :     // Once this stage is complete, reset mDeviceBeingCommissioned - this will be reset when the delegate calls the next step.
    2171              :     MATTER_TRACE_SCOPE("CommissioningStageComplete", "DeviceCommissioner");
    2172              :     MATTER_LOG_METRIC_END(MetricKeyForCommissioningStage(mCommissioningStage), err);
    2173            0 :     VerifyOrDie(mDeviceBeingCommissioned);
    2174              : 
    2175            0 :     NodeId nodeId            = mDeviceBeingCommissioned->GetDeviceId();
    2176            0 :     DeviceProxy * proxy      = mDeviceBeingCommissioned;
    2177            0 :     mDeviceBeingCommissioned = nullptr;
    2178            0 :     mInvokeCancelFn          = nullptr;
    2179            0 :     mWriteCancelFn           = nullptr;
    2180              : 
    2181            0 :     if (mPairingDelegate != nullptr)
    2182              :     {
    2183            0 :         mPairingDelegate->OnCommissioningStatusUpdate(PeerId(GetCompressedFabricId(), nodeId), mCommissioningStage, err);
    2184              :     }
    2185              : 
    2186            0 :     if (mCommissioningDelegate == nullptr)
    2187              :     {
    2188            0 :         return;
    2189              :     }
    2190            0 :     report.stageCompleted = mCommissioningStage;
    2191            0 :     CHIP_ERROR status     = mCommissioningDelegate->CommissioningStepFinished(err, report);
    2192            0 :     if (status != CHIP_NO_ERROR && mCommissioningStage != CommissioningStage::kCleanup)
    2193              :     {
    2194              :         // Commissioning delegate will only return error if it failed to perform the appropriate commissioning step.
    2195              :         // In this case, we should complete the commissioning for it.
    2196            0 :         CompletionStatus completionStatus;
    2197            0 :         completionStatus.err         = status;
    2198            0 :         completionStatus.failedStage = MakeOptional(report.stageCompleted);
    2199            0 :         mCommissioningStage          = CommissioningStage::kCleanup;
    2200            0 :         mDeviceBeingCommissioned     = proxy;
    2201            0 :         CleanupCommissioning(proxy, nodeId, completionStatus);
    2202              :     }
    2203              : }
    2204              : 
    2205            0 : void DeviceCommissioner::OnDeviceConnectedFn(void * context, Messaging::ExchangeManager & exchangeMgr,
    2206              :                                              const SessionHandle & sessionHandle)
    2207              : {
    2208              :     // CASE session established.
    2209              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissioningOperationalSetup, CHIP_NO_ERROR);
    2210            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2211            0 :     VerifyOrDie(commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForStayActive ||
    2212              :                 commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForCommissioningComplete);
    2213            0 :     VerifyOrDie(commissioner->mDeviceBeingCommissioned->GetDeviceId() == sessionHandle->GetPeer().GetNodeId());
    2214            0 :     commissioner->CancelCASECallbacks(); // ensure all CASE callbacks are unregistered
    2215              : 
    2216            0 :     CommissioningDelegate::CommissioningReport report;
    2217            0 :     report.Set<OperationalNodeFoundData>(OperationalNodeFoundData(OperationalDeviceProxy(&exchangeMgr, sessionHandle)));
    2218            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    2219            0 : }
    2220              : 
    2221            0 : void DeviceCommissioner::OnDeviceConnectionFailureFn(void * context, const ScopedNodeId & peerId, CHIP_ERROR error)
    2222              : {
    2223              :     // CASE session establishment failed.
    2224              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissioningOperationalSetup, error);
    2225            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2226            0 :     VerifyOrDie(commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForStayActive ||
    2227              :                 commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForCommissioningComplete);
    2228            0 :     VerifyOrDie(commissioner->mDeviceBeingCommissioned->GetDeviceId() == peerId.GetNodeId());
    2229            0 :     commissioner->CancelCASECallbacks(); // ensure all CASE callbacks are unregistered
    2230              : 
    2231            0 :     if (error != CHIP_NO_ERROR)
    2232              :     {
    2233            0 :         ChipLogProgress(Controller, "Device connection failed. Error %" CHIP_ERROR_FORMAT, error.Format());
    2234              :     }
    2235              :     else
    2236              :     {
    2237              :         // Ensure that commissioning stage advancement is done based on seeing an error.
    2238            0 :         ChipLogError(Controller, "Device connection failed without a valid error code.");
    2239            0 :         error = CHIP_ERROR_INTERNAL;
    2240              :     }
    2241            0 :     commissioner->CommissioningStageComplete(error);
    2242            0 : }
    2243              : 
    2244              : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    2245              : // No specific action to take on either success or failure here; we're just
    2246              : // trying to bump the fail-safe, and if that fails it's not clear there's much
    2247              : // we can to with that.
    2248            0 : static void OnExtendFailsafeForCASERetryFailure(void * context, CHIP_ERROR error)
    2249              : {
    2250            0 :     ChipLogError(Controller, "Failed to extend fail-safe for CASE retry: %" CHIP_ERROR_FORMAT, error.Format());
    2251            0 : }
    2252              : static void
    2253            0 : OnExtendFailsafeForCASERetrySuccess(void * context,
    2254              :                                     const app::Clusters::GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType & data)
    2255              : {
    2256            0 :     ChipLogProgress(Controller, "Status of extending fail-safe for CASE retry: %u", to_underlying(data.errorCode));
    2257            0 : }
    2258              : 
    2259            0 : void DeviceCommissioner::OnDeviceConnectionRetryFn(void * context, const ScopedNodeId & peerId, CHIP_ERROR error,
    2260              :                                                    System::Clock::Seconds16 retryTimeout)
    2261              : {
    2262            0 :     ChipLogError(Controller,
    2263              :                  "Session establishment failed for " ChipLogFormatScopedNodeId ", error: %" CHIP_ERROR_FORMAT
    2264              :                  ".  Next retry expected to get a response to Sigma1 or fail within %d seconds",
    2265              :                  ChipLogValueScopedNodeId(peerId), error.Format(), retryTimeout.count());
    2266              : 
    2267            0 :     auto self = static_cast<DeviceCommissioner *>(context);
    2268            0 :     VerifyOrDie(self->GetCommissioningStage() == CommissioningStage::kFindOperationalForStayActive ||
    2269              :                 self->GetCommissioningStage() == CommissioningStage::kFindOperationalForCommissioningComplete);
    2270            0 :     VerifyOrDie(self->mDeviceBeingCommissioned->GetDeviceId() == peerId.GetNodeId());
    2271              : 
    2272              :     bool supportsConcurrent =
    2273            0 :         self->mCommissioningDelegate->GetCommissioningParameters().GetSupportsConcurrentConnection().ValueOr(true);
    2274            0 :     if (!supportsConcurrent)
    2275              :     {
    2276              :         // Concurrent mode not supported.
    2277              :         // We are in operational phase so the commissioning channel is not
    2278              :         // available anymore and it is not possible to re-arm the fail-safe timer.
    2279            0 :         return;
    2280              :     }
    2281              : 
    2282              :     // We need to do the fail-safe arming over the PASE session.
    2283            0 :     auto * commissioneeDevice = self->FindCommissioneeDevice(peerId.GetNodeId());
    2284            0 :     if (!commissioneeDevice)
    2285              :     {
    2286              :         // Commissioning canceled, presumably.  Just ignore the notification,
    2287              :         // not much we can do here.
    2288            0 :         return;
    2289              :     }
    2290              : 
    2291              :     // Extend by the default failsafe timeout plus our retry timeout, so we can
    2292              :     // be sure the fail-safe will not expire before we try the next time, if
    2293              :     // there will be a next time.
    2294              :     //
    2295              :     // TODO: Make it possible for our clients to control the exact timeout here?
    2296              :     uint16_t failsafeTimeout;
    2297            0 :     if (UINT16_MAX - retryTimeout.count() < kDefaultFailsafeTimeout)
    2298              :     {
    2299            0 :         failsafeTimeout = UINT16_MAX;
    2300              :     }
    2301              :     else
    2302              :     {
    2303            0 :         failsafeTimeout = static_cast<uint16_t>(retryTimeout.count() + kDefaultFailsafeTimeout);
    2304              :     }
    2305              : 
    2306              :     // A false return is fine; we don't want to make the fail-safe shorter here.
    2307            0 :     self->ExtendArmFailSafeInternal(commissioneeDevice, self->GetCommissioningStage(), failsafeTimeout,
    2308            0 :                                     MakeOptional(kMinimumCommissioningStepTimeout), OnExtendFailsafeForCASERetrySuccess,
    2309              :                                     OnExtendFailsafeForCASERetryFailure, /* fireAndForget = */ true);
    2310              : }
    2311              : #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    2312              : 
    2313              : // ClusterStateCache::Callback / ReadClient::Callback
    2314            0 : void DeviceCommissioner::OnDone(app::ReadClient * readClient)
    2315              : {
    2316            0 :     VerifyOrDie(readClient != nullptr && readClient == mReadClient.get());
    2317            0 :     mReadClient.reset();
    2318            0 :     switch (mCommissioningStage)
    2319              :     {
    2320            0 :     case CommissioningStage::kReadCommissioningInfo:
    2321            0 :         ContinueReadingCommissioningInfo(mCommissioningDelegate->GetCommissioningParameters());
    2322            0 :         break;
    2323            0 :     default:
    2324            0 :         VerifyOrDie(false);
    2325              :         break;
    2326              :     }
    2327            0 : }
    2328              : 
    2329              : namespace {
    2330              : // Helper for grouping attribute paths into read interactions in ContinueReadingCommissioningInfo()
    2331              : // below. The logic generates a sequence of calls to AddAttributePath(), stopping when the capacity
    2332              : // of the builder is exceeded. When creating subsequent read requests, the same sequence of calls
    2333              : // is generated again, but the builder will skip however many attributes were already read in
    2334              : // previous requests. This makes it easy to have logic that conditionally reads attributes, without
    2335              : // needing to write manual code to work out where subsequent reads need to resume -- the logic that
    2336              : // decides which attributes to read simply needs to be repeatable / deterministic.
    2337              : class ReadInteractionBuilder
    2338              : {
    2339              :     static constexpr auto kCapacity = InteractionModelEngine::kMinSupportedPathsPerReadRequest;
    2340              : 
    2341              :     size_t mSkip  = 0;
    2342              :     size_t mCount = 0;
    2343              :     app::AttributePathParams mPaths[kCapacity];
    2344              : 
    2345              : public:
    2346            0 :     ReadInteractionBuilder(size_t skip = 0) : mSkip(skip) {}
    2347              : 
    2348            0 :     size_t size() { return std::min(mCount, kCapacity); }
    2349            0 :     bool exceeded() { return mCount > kCapacity; }
    2350            0 :     app::AttributePathParams * paths() { return mPaths; }
    2351              : 
    2352              :     // Adds an attribute path if within the current window.
    2353              :     // Returns false if the available space has been exceeded.
    2354              :     template <typename... Ts>
    2355            0 :     bool AddAttributePath(Ts &&... args)
    2356              :     {
    2357            0 :         if (mSkip > 0)
    2358              :         {
    2359            0 :             mSkip--;
    2360            0 :             return true;
    2361              :         }
    2362            0 :         if (mCount >= kCapacity)
    2363              :         {
    2364              :             // capacity exceeded
    2365            0 :             mCount = kCapacity + 1;
    2366            0 :             return false;
    2367              :         }
    2368            0 :         mPaths[mCount++] = app::AttributePathParams(std::forward<Ts>(args)...);
    2369            0 :         return true;
    2370              :     }
    2371              : };
    2372              : } // namespace
    2373              : 
    2374            0 : void DeviceCommissioner::ContinueReadingCommissioningInfo(const CommissioningParameters & params)
    2375              : {
    2376            0 :     VerifyOrDie(mCommissioningStage == CommissioningStage::kReadCommissioningInfo);
    2377              : 
    2378              :     // mReadCommissioningInfoProgress starts at 0 and counts the number of paths we have read.
    2379              :     // A marker value is used to indicate that there are no further attributes to read.
    2380              :     static constexpr auto kReadProgressNoFurtherAttributes = std::numeric_limits<decltype(mReadCommissioningInfoProgress)>::max();
    2381            0 :     if (mReadCommissioningInfoProgress == kReadProgressNoFurtherAttributes)
    2382              :     {
    2383            0 :         FinishReadingCommissioningInfo(params);
    2384            0 :         return;
    2385              :     }
    2386              : 
    2387              :     // We can ony read 9 paths per Read Interaction, since that is the minimum a server has to
    2388              :     // support per spec (see "Interaction Model Limits"), so we generally need to perform more
    2389              :     // that one interaction. To build the list of attributes for each interaction, we use a
    2390              :     // builder that skips adding paths that we already handled in a previous interaction, and
    2391              :     // returns false if the current request is exhausted. This construction avoids allocating
    2392              :     // memory to hold the complete list of attributes to read up front; however the logic to
    2393              :     // determine the attributes to include must be deterministic since it runs multiple times.
    2394              :     // The use of an immediately-invoked lambda is convenient for control flow.
    2395            0 :     ReadInteractionBuilder builder(mReadCommissioningInfoProgress);
    2396            0 :     [&]() -> void {
    2397              :         // General Commissioning
    2398            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2399              :                                                 Clusters::GeneralCommissioning::Attributes::SupportsConcurrentConnection::Id));
    2400            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2401              :                                                 Clusters::GeneralCommissioning::Attributes::Breadcrumb::Id));
    2402            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2403              :                                                 Clusters::GeneralCommissioning::Attributes::BasicCommissioningInfo::Id));
    2404            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2405              :                                                 Clusters::GeneralCommissioning::Attributes::RegulatoryConfig::Id));
    2406            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2407              :                                                 Clusters::GeneralCommissioning::Attributes::LocationCapability::Id));
    2408            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2409              :                                                 Clusters::GeneralCommissioning::Attributes::IsCommissioningWithoutPower::Id));
    2410              : 
    2411              :         // Basic Information: VID and PID for device attestation purposes
    2412            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::BasicInformation::Id,
    2413              :                                                 Clusters::BasicInformation::Attributes::VendorID::Id));
    2414            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::BasicInformation::Id,
    2415              :                                                 Clusters::BasicInformation::Attributes::ProductID::Id));
    2416              : 
    2417              :         // Time Synchronization: all attributes
    2418            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::TimeSynchronization::Id));
    2419              : 
    2420              :         // Network Commissioning (all endpoints): Read the feature map and connect time
    2421              :         // TODO: Expose a flag that disables network setup so we don't need to read this
    2422            0 :         VerifyOrReturn(builder.AddAttributePath(Clusters::NetworkCommissioning::Id,
    2423              :                                                 Clusters::NetworkCommissioning::Attributes::FeatureMap::Id));
    2424            0 :         VerifyOrReturn(builder.AddAttributePath(Clusters::NetworkCommissioning::Id,
    2425              :                                                 Clusters::NetworkCommissioning::Attributes::ConnectMaxTimeSeconds::Id));
    2426              : 
    2427              :         // If we were asked to do network scans, also read ScanMaxTimeSeconds,
    2428              :         // so we know how long to wait for those.
    2429            0 :         if (params.GetAttemptWiFiNetworkScan().ValueOr(false) || params.GetAttemptThreadNetworkScan().ValueOr(false))
    2430              :         {
    2431            0 :             VerifyOrReturn(builder.AddAttributePath(Clusters::NetworkCommissioning::Id,
    2432              :                                                     Clusters::NetworkCommissioning::Attributes::ScanMaxTimeSeconds::Id));
    2433              :         }
    2434              : 
    2435              :         // OperationalCredentials: existing fabrics, if necessary
    2436            0 :         if (params.GetCheckForMatchingFabric())
    2437              :         {
    2438            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::OperationalCredentials::Id,
    2439              :                                                     Clusters::OperationalCredentials::Attributes::Fabrics::Id));
    2440              :         }
    2441              : 
    2442              :         // ICD Management
    2443            0 :         if (params.GetICDRegistrationStrategy() != ICDRegistrationStrategy::kIgnore)
    2444              :         {
    2445            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2446              :                                                     Clusters::IcdManagement::Attributes::FeatureMap::Id));
    2447            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2448              :                                                     Clusters::IcdManagement::Attributes::UserActiveModeTriggerHint::Id));
    2449            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2450              :                                                     Clusters::IcdManagement::Attributes::UserActiveModeTriggerInstruction::Id));
    2451            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2452              :                                                     Clusters::IcdManagement::Attributes::IdleModeDuration::Id));
    2453            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2454              :                                                     Clusters::IcdManagement::Attributes::ActiveModeDuration::Id));
    2455            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2456              :                                                     Clusters::IcdManagement::Attributes::ActiveModeThreshold::Id));
    2457            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2458              :                                                     Clusters::IcdManagement::Attributes::ClusterRevision::Id));
    2459              :         }
    2460              : 
    2461              :         // Extra paths requested via CommissioningParameters
    2462            0 :         for (auto const & path : params.GetExtraReadPaths())
    2463              :         {
    2464            0 :             VerifyOrReturn(builder.AddAttributePath(path));
    2465              :         }
    2466            0 :     }();
    2467              : 
    2468            0 :     VerifyOrDie(builder.size() > 0); // our logic is broken if there is nothing to read
    2469            0 :     if (builder.exceeded())
    2470              :     {
    2471              :         // Keep track of the number of attributes we have read already so we can resume from there.
    2472            0 :         auto progress = mReadCommissioningInfoProgress + builder.size();
    2473            0 :         VerifyOrDie(progress < kReadProgressNoFurtherAttributes);
    2474            0 :         mReadCommissioningInfoProgress = static_cast<decltype(mReadCommissioningInfoProgress)>(progress);
    2475              :     }
    2476              :     else
    2477              :     {
    2478            0 :         mReadCommissioningInfoProgress = kReadProgressNoFurtherAttributes;
    2479              :     }
    2480              : 
    2481            0 :     SendCommissioningReadRequest(mDeviceBeingCommissioned, mCommissioningStepTimeout, builder.paths(), builder.size());
    2482              : }
    2483              : 
    2484              : namespace {
    2485            0 : void AccumulateErrors(CHIP_ERROR & acc, CHIP_ERROR err)
    2486              : {
    2487            0 :     if (acc == CHIP_NO_ERROR && err != CHIP_NO_ERROR)
    2488              :     {
    2489            0 :         acc = err;
    2490              :     }
    2491            0 : }
    2492              : } // namespace
    2493              : 
    2494            0 : void DeviceCommissioner::FinishReadingCommissioningInfo(const CommissioningParameters & params)
    2495              : {
    2496              :     // We want to parse as much information as possible, even if we eventually end
    2497              :     // up returning an error (e.g. because some mandatory information was missing).
    2498            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    2499            0 :     ReadCommissioningInfo info;
    2500            0 :     info.attributes = mAttributeCache.get();
    2501            0 :     AccumulateErrors(err, ParseGeneralCommissioningInfo(info));
    2502            0 :     AccumulateErrors(err, ParseBasicInformation(info));
    2503            0 :     AccumulateErrors(err, ParseNetworkCommissioningInfo(info));
    2504            0 :     AccumulateErrors(err, ParseTimeSyncInfo(info));
    2505            0 :     AccumulateErrors(err, ParseFabrics(info));
    2506            0 :     AccumulateErrors(err, ParseICDInfo(info));
    2507            0 :     AccumulateErrors(err, ParseExtraCommissioningInfo(info, params));
    2508              : 
    2509            0 :     if (mPairingDelegate != nullptr && err == CHIP_NO_ERROR)
    2510              :     {
    2511            0 :         mPairingDelegate->OnReadCommissioningInfo(info);
    2512              :     }
    2513              : 
    2514            0 :     CommissioningDelegate::CommissioningReport report;
    2515            0 :     report.Set<ReadCommissioningInfo>(info);
    2516            0 :     CommissioningStageComplete(err, report);
    2517              : 
    2518              :     // Only release the attribute cache once `info` is no longer needed.
    2519            0 :     mAttributeCache.reset();
    2520            0 : }
    2521              : 
    2522            0 : CHIP_ERROR DeviceCommissioner::ParseGeneralCommissioningInfo(ReadCommissioningInfo & info)
    2523              : {
    2524              :     using namespace GeneralCommissioning::Attributes;
    2525            0 :     CHIP_ERROR return_err = CHIP_NO_ERROR;
    2526              :     CHIP_ERROR err;
    2527              : 
    2528            0 :     BasicCommissioningInfo::TypeInfo::DecodableType basicInfo;
    2529            0 :     err = mAttributeCache->Get<BasicCommissioningInfo::TypeInfo>(kRootEndpointId, basicInfo);
    2530            0 :     if (err == CHIP_NO_ERROR)
    2531              :     {
    2532            0 :         info.general.recommendedFailsafe = basicInfo.failSafeExpiryLengthSeconds;
    2533              :     }
    2534              :     else
    2535              :     {
    2536            0 :         ChipLogError(Controller, "Failed to read BasicCommissioningInfo: %" CHIP_ERROR_FORMAT, err.Format());
    2537            0 :         return_err = err;
    2538              :     }
    2539              : 
    2540            0 :     err = mAttributeCache->Get<RegulatoryConfig::TypeInfo>(kRootEndpointId, info.general.currentRegulatoryLocation);
    2541            0 :     if (err != CHIP_NO_ERROR)
    2542              :     {
    2543            0 :         ChipLogError(Controller, "Failed to read RegulatoryConfig: %" CHIP_ERROR_FORMAT, err.Format());
    2544            0 :         return_err = err;
    2545              :     }
    2546              : 
    2547            0 :     err = mAttributeCache->Get<LocationCapability::TypeInfo>(kRootEndpointId, info.general.locationCapability);
    2548            0 :     if (err != CHIP_NO_ERROR)
    2549              :     {
    2550            0 :         ChipLogError(Controller, "Failed to read LocationCapability: %" CHIP_ERROR_FORMAT, err.Format());
    2551            0 :         return_err = err;
    2552              :     }
    2553              : 
    2554            0 :     err = mAttributeCache->Get<Breadcrumb::TypeInfo>(kRootEndpointId, info.general.breadcrumb);
    2555            0 :     if (err != CHIP_NO_ERROR)
    2556              :     {
    2557            0 :         ChipLogError(Controller, "Failed to read Breadcrumb: %" CHIP_ERROR_FORMAT, err.Format());
    2558            0 :         return_err = err;
    2559              :     }
    2560              : 
    2561            0 :     err = mAttributeCache->Get<SupportsConcurrentConnection::TypeInfo>(kRootEndpointId, info.supportsConcurrentConnection);
    2562            0 :     if (err != CHIP_NO_ERROR)
    2563              :     {
    2564            0 :         ChipLogError(Controller, "Ignoring failure to read SupportsConcurrentConnection: %" CHIP_ERROR_FORMAT, err.Format());
    2565            0 :         info.supportsConcurrentConnection = true; // default to true (concurrent), not a fatal error
    2566              :     }
    2567              : 
    2568            0 :     err = mAttributeCache->Get<IsCommissioningWithoutPower::TypeInfo>(kRootEndpointId, info.general.isCommissioningWithoutPower);
    2569            0 :     if (err != CHIP_NO_ERROR)
    2570              :     {
    2571              :         // 'IsCommissioningWithoutPower' is optional. Any failures (likely not present) means default to assuming false.
    2572            0 :         info.general.isCommissioningWithoutPower = false;
    2573              :     }
    2574              : 
    2575            0 :     return return_err;
    2576              : }
    2577              : 
    2578            0 : CHIP_ERROR DeviceCommissioner::ParseBasicInformation(ReadCommissioningInfo & info)
    2579              : {
    2580              :     using namespace BasicInformation::Attributes;
    2581            0 :     CHIP_ERROR return_err = CHIP_NO_ERROR;
    2582              :     CHIP_ERROR err;
    2583              : 
    2584            0 :     err = mAttributeCache->Get<VendorID::TypeInfo>(kRootEndpointId, info.basic.vendorId);
    2585            0 :     if (err != CHIP_NO_ERROR)
    2586              :     {
    2587            0 :         ChipLogError(Controller, "Failed to read VendorID: %" CHIP_ERROR_FORMAT, err.Format());
    2588            0 :         return_err = err;
    2589              :     }
    2590              : 
    2591            0 :     err = mAttributeCache->Get<ProductID::TypeInfo>(kRootEndpointId, info.basic.productId);
    2592            0 :     if (err != CHIP_NO_ERROR)
    2593              :     {
    2594            0 :         ChipLogError(Controller, "Failed to read ProductID: %" CHIP_ERROR_FORMAT, err.Format());
    2595            0 :         return_err = err;
    2596              :     }
    2597              : 
    2598            0 :     return return_err;
    2599              : }
    2600              : 
    2601            0 : CHIP_ERROR DeviceCommissioner::ParseNetworkCommissioningInfo(ReadCommissioningInfo & info)
    2602              : {
    2603              :     using namespace NetworkCommissioning::Attributes;
    2604            0 :     CHIP_ERROR return_err = CHIP_NO_ERROR;
    2605              :     CHIP_ERROR err;
    2606              : 
    2607              :     // Set the network cluster endpoints first so we can match up the connection
    2608              :     // times. Note that here we don't know what endpoints the network
    2609              :     // commissioning clusters might be on.
    2610            0 :     err = mAttributeCache->ForEachAttribute(NetworkCommissioning::Id, [this, &info](const ConcreteAttributePath & path) {
    2611            0 :         VerifyOrReturnError(path.mAttributeId == FeatureMap::Id, CHIP_NO_ERROR);
    2612            0 :         BitFlags<NetworkCommissioning::Feature> features;
    2613            0 :         if (mAttributeCache->Get<FeatureMap::TypeInfo>(path, *features.RawStorage()) == CHIP_NO_ERROR)
    2614              :         {
    2615            0 :             if (features.Has(NetworkCommissioning::Feature::kWiFiNetworkInterface))
    2616              :             {
    2617            0 :                 ChipLogProgress(Controller, "NetworkCommissioning Features: has WiFi. endpointid = %u", path.mEndpointId);
    2618            0 :                 info.network.wifi.endpoint = path.mEndpointId;
    2619              :             }
    2620            0 :             else if (features.Has(NetworkCommissioning::Feature::kThreadNetworkInterface))
    2621              :             {
    2622            0 :                 ChipLogProgress(Controller, "NetworkCommissioning Features: has Thread. endpointid = %u", path.mEndpointId);
    2623            0 :                 info.network.thread.endpoint = path.mEndpointId;
    2624              :             }
    2625            0 :             else if (features.Has(NetworkCommissioning::Feature::kEthernetNetworkInterface))
    2626              :             {
    2627            0 :                 ChipLogProgress(Controller, "NetworkCommissioning Features: has Ethernet. endpointid = %u", path.mEndpointId);
    2628            0 :                 info.network.eth.endpoint = path.mEndpointId;
    2629              :             }
    2630              :         }
    2631            0 :         return CHIP_NO_ERROR;
    2632              :     });
    2633            0 :     AccumulateErrors(return_err, err);
    2634              : 
    2635            0 :     if (info.network.thread.endpoint != kInvalidEndpointId)
    2636              :     {
    2637            0 :         err = ParseNetworkCommissioningTimeouts(info.network.thread, "Thread");
    2638            0 :         AccumulateErrors(return_err, err);
    2639              :     }
    2640              : 
    2641            0 :     if (info.network.wifi.endpoint != kInvalidEndpointId)
    2642              :     {
    2643            0 :         err = ParseNetworkCommissioningTimeouts(info.network.wifi, "Wi-Fi");
    2644            0 :         AccumulateErrors(return_err, err);
    2645              :     }
    2646              : 
    2647            0 :     if (return_err != CHIP_NO_ERROR)
    2648              :     {
    2649            0 :         ChipLogError(Controller, "Failed to parse Network Commissioning information: %" CHIP_ERROR_FORMAT, return_err.Format());
    2650              :     }
    2651            0 :     return return_err;
    2652              : }
    2653              : 
    2654            0 : CHIP_ERROR DeviceCommissioner::ParseNetworkCommissioningTimeouts(NetworkClusterInfo & networkInfo, const char * networkType)
    2655              : {
    2656              :     using namespace NetworkCommissioning::Attributes;
    2657              : 
    2658            0 :     CHIP_ERROR err = mAttributeCache->Get<ConnectMaxTimeSeconds::TypeInfo>(networkInfo.endpoint, networkInfo.minConnectionTime);
    2659            0 :     if (err != CHIP_NO_ERROR)
    2660              :     {
    2661            0 :         ChipLogError(Controller, "Failed to read %s ConnectMaxTimeSeconds (endpoint %u): %" CHIP_ERROR_FORMAT, networkType,
    2662              :                      networkInfo.endpoint, err.Format());
    2663            0 :         return err;
    2664              :     }
    2665              : 
    2666            0 :     err = mAttributeCache->Get<ScanMaxTimeSeconds::TypeInfo>(networkInfo.endpoint, networkInfo.maxScanTime);
    2667            0 :     if (err != CHIP_NO_ERROR)
    2668              :     {
    2669              :         // We don't always read this attribute, and we read it as a wildcard, so
    2670              :         // don't treat it as an error simply because it's missing.
    2671            0 :         if (err != CHIP_ERROR_KEY_NOT_FOUND)
    2672              :         {
    2673            0 :             ChipLogError(Controller, "Failed to read %s ScanMaxTimeSeconds (endpoint: %u): %" CHIP_ERROR_FORMAT, networkType,
    2674              :                          networkInfo.endpoint, err.Format());
    2675            0 :             return err;
    2676              :         }
    2677              : 
    2678              :         // Just flag as "we don't know".
    2679            0 :         networkInfo.maxScanTime = 0;
    2680              :     }
    2681              : 
    2682            0 :     return CHIP_NO_ERROR;
    2683              : }
    2684              : 
    2685            0 : CHIP_ERROR DeviceCommissioner::ParseTimeSyncInfo(ReadCommissioningInfo & info)
    2686              : {
    2687              :     using namespace TimeSynchronization::Attributes;
    2688              :     CHIP_ERROR err;
    2689              : 
    2690              :     // If we fail to get the feature map, there's no viable time cluster, don't set anything.
    2691            0 :     BitFlags<TimeSynchronization::Feature> featureMap;
    2692            0 :     err = mAttributeCache->Get<FeatureMap::TypeInfo>(kRootEndpointId, *featureMap.RawStorage());
    2693            0 :     if (err != CHIP_NO_ERROR)
    2694              :     {
    2695            0 :         info.requiresUTC               = false;
    2696            0 :         info.requiresTimeZone          = false;
    2697            0 :         info.requiresDefaultNTP        = false;
    2698            0 :         info.requiresTrustedTimeSource = false;
    2699            0 :         return CHIP_NO_ERROR;
    2700              :     }
    2701            0 :     info.requiresUTC               = true;
    2702            0 :     info.requiresTimeZone          = featureMap.Has(TimeSynchronization::Feature::kTimeZone);
    2703            0 :     info.requiresDefaultNTP        = featureMap.Has(TimeSynchronization::Feature::kNTPClient);
    2704            0 :     info.requiresTrustedTimeSource = featureMap.Has(TimeSynchronization::Feature::kTimeSyncClient);
    2705              : 
    2706            0 :     if (info.requiresTimeZone)
    2707              :     {
    2708            0 :         err = mAttributeCache->Get<TimeZoneListMaxSize::TypeInfo>(kRootEndpointId, info.maxTimeZoneSize);
    2709            0 :         if (err != CHIP_NO_ERROR)
    2710              :         {
    2711              :             // This information should be available, let's do our best with what we have, but we can't set
    2712              :             // the time zone without this information
    2713            0 :             info.requiresTimeZone = false;
    2714              :         }
    2715            0 :         err = mAttributeCache->Get<DSTOffsetListMaxSize::TypeInfo>(kRootEndpointId, info.maxDSTSize);
    2716            0 :         if (err != CHIP_NO_ERROR)
    2717              :         {
    2718            0 :             info.requiresTimeZone = false;
    2719              :         }
    2720              :     }
    2721            0 :     if (info.requiresDefaultNTP)
    2722              :     {
    2723            0 :         DefaultNTP::TypeInfo::DecodableType defaultNTP;
    2724            0 :         err = mAttributeCache->Get<DefaultNTP::TypeInfo>(kRootEndpointId, defaultNTP);
    2725            0 :         if (err == CHIP_NO_ERROR && (!defaultNTP.IsNull()) && (defaultNTP.Value().size() != 0))
    2726              :         {
    2727            0 :             info.requiresDefaultNTP = false;
    2728              :         }
    2729              :     }
    2730            0 :     if (info.requiresTrustedTimeSource)
    2731              :     {
    2732            0 :         TrustedTimeSource::TypeInfo::DecodableType trustedTimeSource;
    2733            0 :         err = mAttributeCache->Get<TrustedTimeSource::TypeInfo>(kRootEndpointId, trustedTimeSource);
    2734            0 :         if (err == CHIP_NO_ERROR && !trustedTimeSource.IsNull())
    2735              :         {
    2736            0 :             info.requiresTrustedTimeSource = false;
    2737              :         }
    2738              :     }
    2739              : 
    2740            0 :     return CHIP_NO_ERROR;
    2741              : }
    2742              : 
    2743            0 : CHIP_ERROR DeviceCommissioner::ParseFabrics(ReadCommissioningInfo & info)
    2744              : {
    2745              :     using namespace OperationalCredentials::Attributes;
    2746              :     CHIP_ERROR err;
    2747            0 :     CHIP_ERROR return_err = CHIP_NO_ERROR;
    2748              : 
    2749              :     // We might not have requested a Fabrics attribute at all, so not having a
    2750              :     // value for it is not an error.
    2751            0 :     err = mAttributeCache->ForEachAttribute(OperationalCredentials::Id, [this, &info](const ConcreteAttributePath & path) {
    2752              :         using namespace chip::app::Clusters::OperationalCredentials::Attributes;
    2753              :         // this code is checking if the device is already on the commissioner's fabric.
    2754              :         // if a matching fabric is found, then remember the nodeId so that the commissioner
    2755              :         // can, if it decides to, cancel commissioning (before it fails in AddNoc) and know
    2756              :         // the device's nodeId on its fabric.
    2757            0 :         switch (path.mAttributeId)
    2758              :         {
    2759            0 :         case Fabrics::Id: {
    2760            0 :             Fabrics::TypeInfo::DecodableType fabrics;
    2761            0 :             ReturnErrorOnFailure(this->mAttributeCache->Get<Fabrics::TypeInfo>(path, fabrics));
    2762              :             // this is a best effort attempt to find a matching fabric, so no error checking on iter
    2763            0 :             auto iter = fabrics.begin();
    2764            0 :             while (iter.Next())
    2765              :             {
    2766            0 :                 auto & fabricDescriptor = iter.GetValue();
    2767            0 :                 ChipLogProgress(Controller,
    2768              :                                 "DeviceCommissioner::OnDone - fabric.vendorId=0x%04X fabric.fabricId=0x" ChipLogFormatX64
    2769              :                                 " fabric.nodeId=0x" ChipLogFormatX64,
    2770              :                                 fabricDescriptor.vendorID, ChipLogValueX64(fabricDescriptor.fabricID),
    2771              :                                 ChipLogValueX64(fabricDescriptor.nodeID));
    2772            0 :                 if (GetFabricId() == fabricDescriptor.fabricID)
    2773              :                 {
    2774            0 :                     ChipLogProgress(Controller, "DeviceCommissioner::OnDone - found a matching fabric id");
    2775            0 :                     chip::ByteSpan rootKeySpan = fabricDescriptor.rootPublicKey;
    2776            0 :                     if (rootKeySpan.size() != Crypto::kP256_PublicKey_Length)
    2777              :                     {
    2778            0 :                         ChipLogError(Controller, "DeviceCommissioner::OnDone - fabric root key size mismatch %u != %u",
    2779              :                                      static_cast<unsigned>(rootKeySpan.size()),
    2780              :                                      static_cast<unsigned>(Crypto::kP256_PublicKey_Length));
    2781            0 :                         continue;
    2782              :                     }
    2783            0 :                     P256PublicKeySpan rootPubKeySpan(rootKeySpan.data());
    2784            0 :                     Crypto::P256PublicKey deviceRootPublicKey(rootPubKeySpan);
    2785              : 
    2786            0 :                     Crypto::P256PublicKey commissionerRootPublicKey;
    2787            0 :                     if (CHIP_NO_ERROR != GetRootPublicKey(commissionerRootPublicKey))
    2788              :                     {
    2789            0 :                         ChipLogError(Controller, "DeviceCommissioner::OnDone - error reading commissioner root public key");
    2790              :                     }
    2791            0 :                     else if (commissionerRootPublicKey.Matches(deviceRootPublicKey))
    2792              :                     {
    2793            0 :                         ChipLogProgress(Controller, "DeviceCommissioner::OnDone - fabric root keys match");
    2794            0 :                         info.remoteNodeId = fabricDescriptor.nodeID;
    2795              :                     }
    2796            0 :                 }
    2797              :             }
    2798              : 
    2799            0 :             return CHIP_NO_ERROR;
    2800              :         }
    2801            0 :         default:
    2802            0 :             return CHIP_NO_ERROR;
    2803              :         }
    2804              :     });
    2805              : 
    2806            0 :     if (mPairingDelegate != nullptr)
    2807              :     {
    2808            0 :         mPairingDelegate->OnFabricCheck(info.remoteNodeId);
    2809              :     }
    2810              : 
    2811            0 :     return return_err;
    2812              : }
    2813              : 
    2814            2 : CHIP_ERROR DeviceCommissioner::ParseICDInfo(ReadCommissioningInfo & info)
    2815              : {
    2816              :     using namespace IcdManagement::Attributes;
    2817              :     CHIP_ERROR err;
    2818              : 
    2819            2 :     bool hasUserActiveModeTrigger = false;
    2820            2 :     bool isICD                    = false;
    2821              : 
    2822            2 :     BitFlags<IcdManagement::Feature> featureMap;
    2823            2 :     err = mAttributeCache->Get<FeatureMap::TypeInfo>(kRootEndpointId, *featureMap.RawStorage());
    2824            4 :     if (err == CHIP_NO_ERROR)
    2825              :     {
    2826            2 :         info.icd.isLIT                  = featureMap.Has(IcdManagement::Feature::kLongIdleTimeSupport);
    2827            2 :         info.icd.checkInProtocolSupport = featureMap.Has(IcdManagement::Feature::kCheckInProtocolSupport);
    2828            2 :         hasUserActiveModeTrigger        = featureMap.Has(IcdManagement::Feature::kUserActiveModeTrigger);
    2829            2 :         isICD                           = true;
    2830              : 
    2831              :         // LIT support was introduced but broken in ICD Management cluster revision 2 (Matter 1.3).
    2832              :         // Only treat a device as LIT for cluster revisions after 1.3 (i.e., revision > 2).
    2833            2 :         if (info.icd.isLIT)
    2834              :         {
    2835            2 :             uint16_t clusterRevision = 0;
    2836            2 :             CHIP_ERROR revErr        = mAttributeCache->Get<ClusterRevision::TypeInfo>(kRootEndpointId, clusterRevision);
    2837            4 :             if (revErr != CHIP_NO_ERROR || clusterRevision <= 2)
    2838              :             {
    2839            2 :                 if (revErr == CHIP_NO_ERROR)
    2840              :                 {
    2841            1 :                     ChipLogProgress(Controller,
    2842              :                                     "IcdManagement: Device claims LIT support but cluster revision is %" PRIu16
    2843              :                                     " (Matter 1.3). Disabling LIT due to known Matter 1.3 LIT issues.",
    2844              :                                     clusterRevision);
    2845              :                 }
    2846              :                 else
    2847              :                 {
    2848            0 :                     ChipLogProgress(Controller,
    2849              :                                     "IcdManagement: Device claims LIT support but ClusterRevision attribute is "
    2850              :                                     "missing or unreadable (err=%" CHIP_ERROR_FORMAT
    2851              :                                     "). Treating as revision <= 2 and disabling LIT.",
    2852              :                                     revErr.Format());
    2853              :                 }
    2854            1 :                 info.icd.isLIT = false;
    2855              :             }
    2856              :         }
    2857              :     }
    2858            0 :     else if (err == CHIP_ERROR_KEY_NOT_FOUND)
    2859              :     {
    2860              :         // This key is optional so not an error
    2861            0 :         info.icd.isLIT = false;
    2862            0 :         err            = CHIP_NO_ERROR;
    2863              :     }
    2864            0 :     else if (err == CHIP_ERROR_IM_STATUS_CODE_RECEIVED)
    2865              :     {
    2866            0 :         app::StatusIB statusIB;
    2867            0 :         err = mAttributeCache->GetStatus(app::ConcreteAttributePath(kRootEndpointId, IcdManagement::Id, FeatureMap::Id), statusIB);
    2868            0 :         if (err == CHIP_NO_ERROR)
    2869              :         {
    2870            0 :             if (statusIB.mStatus == Protocols::InteractionModel::Status::UnsupportedCluster)
    2871              :             {
    2872            0 :                 info.icd.isLIT = false;
    2873              :             }
    2874              :             else
    2875              :             {
    2876            0 :                 err = statusIB.ToChipError();
    2877              :             }
    2878              :         }
    2879              :     }
    2880              : 
    2881            2 :     ReturnErrorOnFailure(err);
    2882              : 
    2883            2 :     info.icd.userActiveModeTriggerHint.ClearAll();
    2884            2 :     info.icd.userActiveModeTriggerInstruction = CharSpan();
    2885              : 
    2886            2 :     if (hasUserActiveModeTrigger)
    2887              :     {
    2888              :         // Intentionally ignore errors since they are not mandatory.
    2889            0 :         bool activeModeTriggerInstructionRequired = false;
    2890              : 
    2891            0 :         err = mAttributeCache->Get<UserActiveModeTriggerHint::TypeInfo>(kRootEndpointId, info.icd.userActiveModeTriggerHint);
    2892            0 :         if (err != CHIP_NO_ERROR)
    2893              :         {
    2894            0 :             ChipLogError(Controller, "IcdManagement.UserActiveModeTriggerHint expected, but failed to read.");
    2895            0 :             return err;
    2896              :         }
    2897              : 
    2898              :         using IcdManagement::UserActiveModeTriggerBitmap;
    2899            0 :         activeModeTriggerInstructionRequired = info.icd.userActiveModeTriggerHint.HasAny(
    2900            0 :             UserActiveModeTriggerBitmap::kCustomInstruction, UserActiveModeTriggerBitmap::kActuateSensorSeconds,
    2901            0 :             UserActiveModeTriggerBitmap::kActuateSensorTimes, UserActiveModeTriggerBitmap::kActuateSensorLightsBlink,
    2902            0 :             UserActiveModeTriggerBitmap::kResetButtonLightsBlink, UserActiveModeTriggerBitmap::kResetButtonSeconds,
    2903            0 :             UserActiveModeTriggerBitmap::kResetButtonTimes, UserActiveModeTriggerBitmap::kSetupButtonSeconds,
    2904            0 :             UserActiveModeTriggerBitmap::kSetupButtonTimes, UserActiveModeTriggerBitmap::kSetupButtonTimes,
    2905            0 :             UserActiveModeTriggerBitmap::kAppDefinedButton);
    2906              : 
    2907            0 :         if (activeModeTriggerInstructionRequired)
    2908              :         {
    2909            0 :             err = mAttributeCache->Get<UserActiveModeTriggerInstruction::TypeInfo>(kRootEndpointId,
    2910            0 :                                                                                    info.icd.userActiveModeTriggerInstruction);
    2911            0 :             if (err != CHIP_NO_ERROR)
    2912              :             {
    2913            0 :                 ChipLogError(Controller,
    2914              :                              "IcdManagement.UserActiveModeTriggerInstruction expected for given active mode trigger hint, but "
    2915              :                              "failed to read.");
    2916            0 :                 return err;
    2917              :             }
    2918              :         }
    2919              :     }
    2920              : 
    2921            2 :     if (!isICD)
    2922              :     {
    2923            0 :         info.icd.idleModeDuration    = 0;
    2924            0 :         info.icd.activeModeDuration  = 0;
    2925            0 :         info.icd.activeModeThreshold = 0;
    2926            0 :         return CHIP_NO_ERROR;
    2927              :     }
    2928              : 
    2929            2 :     err = mAttributeCache->Get<IdleModeDuration::TypeInfo>(kRootEndpointId, info.icd.idleModeDuration);
    2930            4 :     if (err != CHIP_NO_ERROR)
    2931              :     {
    2932            0 :         ChipLogError(Controller, "IcdManagement.IdleModeDuration expected, but failed to read: %" CHIP_ERROR_FORMAT, err.Format());
    2933            0 :         return err;
    2934              :     }
    2935              : 
    2936            2 :     err = mAttributeCache->Get<ActiveModeDuration::TypeInfo>(kRootEndpointId, info.icd.activeModeDuration);
    2937            4 :     if (err != CHIP_NO_ERROR)
    2938              :     {
    2939            0 :         ChipLogError(Controller, "IcdManagement.ActiveModeDuration expected, but failed to read: %" CHIP_ERROR_FORMAT,
    2940              :                      err.Format());
    2941            0 :         return err;
    2942              :     }
    2943              : 
    2944            2 :     err = mAttributeCache->Get<ActiveModeThreshold::TypeInfo>(kRootEndpointId, info.icd.activeModeThreshold);
    2945            4 :     if (err != CHIP_NO_ERROR)
    2946              :     {
    2947            0 :         ChipLogError(Controller, "IcdManagement.ActiveModeThreshold expected, but failed to read: %" CHIP_ERROR_FORMAT,
    2948              :                      err.Format());
    2949              :     }
    2950              : 
    2951            2 :     return err;
    2952              : }
    2953              : 
    2954            0 : void DeviceCommissioner::OnArmFailSafe(void * context,
    2955              :                                        const GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType & data)
    2956              : {
    2957            0 :     CommissioningDelegate::CommissioningReport report;
    2958            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    2959              : 
    2960            0 :     ChipLogProgress(Controller, "Received ArmFailSafe response errorCode=%u", to_underlying(data.errorCode));
    2961            0 :     if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
    2962              :     {
    2963            0 :         err = CHIP_ERROR_INTERNAL;
    2964            0 :         report.Set<CommissioningErrorInfo>(data.errorCode);
    2965              :     }
    2966              : 
    2967            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2968            0 :     commissioner->CommissioningStageComplete(err, report);
    2969            0 : }
    2970              : 
    2971            0 : void DeviceCommissioner::OnSetRegulatoryConfigResponse(
    2972              :     void * context, const GeneralCommissioning::Commands::SetRegulatoryConfigResponse::DecodableType & data)
    2973              : {
    2974            0 :     CommissioningDelegate::CommissioningReport report;
    2975            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    2976              : 
    2977            0 :     ChipLogProgress(Controller, "Received SetRegulatoryConfig response errorCode=%u", to_underlying(data.errorCode));
    2978            0 :     if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
    2979              :     {
    2980            0 :         err = CHIP_ERROR_INTERNAL;
    2981            0 :         report.Set<CommissioningErrorInfo>(data.errorCode);
    2982              :     }
    2983            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2984            0 :     commissioner->CommissioningStageComplete(err, report);
    2985            0 : }
    2986              : 
    2987            0 : void DeviceCommissioner::OnSetTCAcknowledgementsResponse(
    2988              :     void * context, const GeneralCommissioning::Commands::SetTCAcknowledgementsResponse::DecodableType & data)
    2989              : {
    2990            0 :     CommissioningDelegate::CommissioningReport report;
    2991            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    2992              : 
    2993            0 :     ChipLogProgress(Controller, "Received SetTCAcknowledgements response errorCode=%u", to_underlying(data.errorCode));
    2994            0 :     if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
    2995              :     {
    2996            0 :         err = CHIP_ERROR_INTERNAL;
    2997            0 :         report.Set<CommissioningErrorInfo>(data.errorCode);
    2998              :     }
    2999            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3000            0 :     commissioner->CommissioningStageComplete(err, report);
    3001            0 : }
    3002              : 
    3003            0 : void DeviceCommissioner::OnSetTimeZoneResponse(void * context,
    3004              :                                                const TimeSynchronization::Commands::SetTimeZoneResponse::DecodableType & data)
    3005              : {
    3006            0 :     CommissioningDelegate::CommissioningReport report;
    3007            0 :     CHIP_ERROR err                    = CHIP_NO_ERROR;
    3008            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3009              :     TimeZoneResponseInfo info;
    3010            0 :     info.requiresDSTOffsets = data.DSTOffsetRequired;
    3011            0 :     report.Set<TimeZoneResponseInfo>(info);
    3012            0 :     commissioner->CommissioningStageComplete(err, report);
    3013            0 : }
    3014              : 
    3015            0 : void DeviceCommissioner::OnSetUTCError(void * context, CHIP_ERROR error)
    3016              : {
    3017              :     // For SetUTCTime, we don't actually care if the commissionee didn't want out time, that's its choice
    3018            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3019            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    3020            0 : }
    3021              : 
    3022            0 : void DeviceCommissioner::OnScanNetworksFailure(void * context, CHIP_ERROR error)
    3023              : {
    3024            0 :     ChipLogProgress(Controller, "Received ScanNetworks failure response %" CHIP_ERROR_FORMAT, error.Format());
    3025              : 
    3026            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3027              : 
    3028              :     // advance to the kNeedsNetworkCreds waiting step
    3029              :     // clear error so that we don't abort the commissioning when ScanNetworks fails
    3030            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    3031              : 
    3032            0 :     if (commissioner->GetPairingDelegate() != nullptr)
    3033              :     {
    3034            0 :         commissioner->GetPairingDelegate()->OnScanNetworksFailure(error);
    3035              :     }
    3036            0 : }
    3037              : 
    3038            0 : void DeviceCommissioner::OnScanNetworksResponse(void * context,
    3039              :                                                 const NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data)
    3040              : {
    3041            0 :     CommissioningDelegate::CommissioningReport report;
    3042              : 
    3043            0 :     ChipLogProgress(Controller, "Received ScanNetwork response, networkingStatus=%u debugText=%s",
    3044              :                     to_underlying(data.networkingStatus),
    3045              :                     (data.debugText.HasValue() ? std::string(data.debugText.Value().data(), data.debugText.Value().size()).c_str()
    3046              :                                                : "none provided"));
    3047            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3048              : 
    3049              :     // advance to the kNeedsNetworkCreds waiting step
    3050            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    3051              : 
    3052            0 :     if (commissioner->GetPairingDelegate() != nullptr)
    3053              :     {
    3054            0 :         commissioner->GetPairingDelegate()->OnScanNetworksSuccess(data);
    3055              :     }
    3056            0 : }
    3057              : 
    3058            0 : CHIP_ERROR DeviceCommissioner::NetworkCredentialsReady()
    3059              : {
    3060            0 :     VerifyOrReturnError(mCommissioningStage == CommissioningStage::kNeedsNetworkCreds, CHIP_ERROR_INCORRECT_STATE);
    3061              : 
    3062              :     // need to advance to next step
    3063            0 :     CommissioningStageComplete(CHIP_NO_ERROR);
    3064              : 
    3065            0 :     return CHIP_NO_ERROR;
    3066              : }
    3067              : 
    3068            0 : CHIP_ERROR DeviceCommissioner::ICDRegistrationInfoReady()
    3069              : {
    3070            0 :     VerifyOrReturnError(mCommissioningStage == CommissioningStage::kICDGetRegistrationInfo, CHIP_ERROR_INCORRECT_STATE);
    3071              : 
    3072              :     // need to advance to next step
    3073            0 :     CommissioningStageComplete(CHIP_NO_ERROR);
    3074              : 
    3075            0 :     return CHIP_NO_ERROR;
    3076              : }
    3077              : 
    3078            0 : void DeviceCommissioner::OnNetworkConfigResponse(void * context,
    3079              :                                                  const NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data)
    3080              : {
    3081            0 :     CommissioningDelegate::CommissioningReport report;
    3082            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    3083              : 
    3084            0 :     ChipLogProgress(Controller, "Received NetworkConfig response, networkingStatus=%u", to_underlying(data.networkingStatus));
    3085            0 :     if (data.networkingStatus != NetworkCommissioning::NetworkCommissioningStatusEnum::kSuccess)
    3086              :     {
    3087            0 :         err = CHIP_ERROR_INTERNAL;
    3088            0 :         report.Set<NetworkCommissioningStatusInfo>(data.networkingStatus);
    3089              :     }
    3090            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3091            0 :     commissioner->CommissioningStageComplete(err, report);
    3092            0 : }
    3093              : 
    3094            0 : void DeviceCommissioner::OnConnectNetworkResponse(
    3095              :     void * context, const NetworkCommissioning::Commands::ConnectNetworkResponse::DecodableType & data)
    3096              : {
    3097            0 :     CommissioningDelegate::CommissioningReport report;
    3098            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    3099              : 
    3100            0 :     ChipLogProgress(Controller, "Received ConnectNetwork response, networkingStatus=%u", to_underlying(data.networkingStatus));
    3101            0 :     if (data.networkingStatus != NetworkCommissioning::NetworkCommissioningStatusEnum::kSuccess)
    3102              :     {
    3103            0 :         err = CHIP_ERROR_INTERNAL;
    3104            0 :         report.Set<NetworkCommissioningStatusInfo>(data.networkingStatus);
    3105              :     }
    3106            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3107            0 :     commissioner->CommissioningStageComplete(err, report);
    3108            0 : }
    3109              : 
    3110            0 : void DeviceCommissioner::OnCommissioningCompleteResponse(
    3111              :     void * context, const GeneralCommissioning::Commands::CommissioningCompleteResponse::DecodableType & data)
    3112              : {
    3113            0 :     CommissioningDelegate::CommissioningReport report;
    3114            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    3115              : 
    3116            0 :     ChipLogProgress(Controller, "Received CommissioningComplete response, errorCode=%u", to_underlying(data.errorCode));
    3117            0 :     if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
    3118              :     {
    3119            0 :         err = CHIP_ERROR_INTERNAL;
    3120            0 :         report.Set<CommissioningErrorInfo>(data.errorCode);
    3121              :     }
    3122            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3123            0 :     commissioner->CommissioningStageComplete(err, report);
    3124            0 : }
    3125              : 
    3126              : template <typename RequestObjectT>
    3127              : CHIP_ERROR
    3128            0 : DeviceCommissioner::SendCommissioningCommand(DeviceProxy * device, const RequestObjectT & request,
    3129              :                                              CommandResponseSuccessCallback<typename RequestObjectT::ResponseType> successCb,
    3130              :                                              CommandResponseFailureCallback failureCb, EndpointId endpoint,
    3131              :                                              Optional<System::Clock::Timeout> timeout, bool fireAndForget)
    3132              : 
    3133              : {
    3134              :     // Default behavior is to make sequential, cancellable calls tracked via mInvokeCancelFn.
    3135              :     // Fire-and-forget calls are not cancellable and don't receive `this` as context in callbacks.
    3136            0 :     VerifyOrDie(fireAndForget || !mInvokeCancelFn); // we don't make parallel (cancellable) calls
    3137              : 
    3138            0 :     void * context   = (!fireAndForget) ? this : nullptr;
    3139            0 :     auto onSuccessCb = [context, successCb](const app::ConcreteCommandPath & aPath, const app::StatusIB & aStatus,
    3140              :                                             const typename RequestObjectT::ResponseType & responseData) {
    3141            0 :         successCb(context, responseData);
    3142              :     };
    3143            0 :     auto onFailureCb = [context, failureCb](CHIP_ERROR aError) { failureCb(context, aError); };
    3144              : 
    3145            0 :     return InvokeCommandRequest(device->GetExchangeManager(), device->GetSecureSession().Value(), endpoint, request, onSuccessCb,
    3146            0 :                                 onFailureCb, NullOptional, timeout, (!fireAndForget) ? &mInvokeCancelFn : nullptr);
    3147              : }
    3148              : 
    3149              : template <typename AttrType>
    3150              : CHIP_ERROR DeviceCommissioner::SendCommissioningWriteRequest(DeviceProxy * device, EndpointId endpoint, ClusterId cluster,
    3151              :                                                              AttributeId attribute, const AttrType & requestData,
    3152              :                                                              WriteResponseSuccessCallback successCb,
    3153              :                                                              WriteResponseFailureCallback failureCb)
    3154              : {
    3155              :     VerifyOrDie(!mWriteCancelFn); // we don't make parallel (cancellable) calls
    3156              :     auto onSuccessCb = [this, successCb](const app::ConcreteAttributePath & aPath) { successCb(this); };
    3157              :     auto onFailureCb = [this, failureCb](const app::ConcreteAttributePath * aPath, CHIP_ERROR aError) { failureCb(this, aError); };
    3158              :     return WriteAttribute(device->GetSecureSession().Value(), endpoint, cluster, attribute, requestData, onSuccessCb, onFailureCb,
    3159              :                           /* aTimedWriteTimeoutMs = */ NullOptional, /* onDoneCb = */ nullptr, /* aDataVersion = */ NullOptional,
    3160              :                           /* outCancelFn = */ &mWriteCancelFn);
    3161              : }
    3162              : 
    3163            0 : void DeviceCommissioner::SendCommissioningReadRequest(DeviceProxy * proxy, Optional<System::Clock::Timeout> timeout,
    3164              :                                                       app::AttributePathParams * readPaths, size_t readPathsSize)
    3165              : {
    3166            0 :     VerifyOrDie(!mReadClient); // we don't perform parallel reads
    3167              : 
    3168            0 :     app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance();
    3169            0 :     app::ReadPrepareParams readParams(proxy->GetSecureSession().Value());
    3170            0 :     readParams.mIsFabricFiltered = false;
    3171            0 :     if (timeout.HasValue())
    3172              :     {
    3173            0 :         readParams.mTimeout = timeout.Value();
    3174              :     }
    3175            0 :     readParams.mpAttributePathParamsList    = readPaths;
    3176            0 :     readParams.mAttributePathParamsListSize = readPathsSize;
    3177              : 
    3178              :     // Take ownership of the attribute cache, so it can be released if SendRequest fails.
    3179            0 :     auto attributeCache = std::move(mAttributeCache);
    3180              :     auto readClient     = chip::Platform::MakeUnique<app::ReadClient>(
    3181            0 :         engine, proxy->GetExchangeManager(), attributeCache->GetBufferedCallback(), app::ReadClient::InteractionType::Read);
    3182            0 :     CHIP_ERROR err = readClient->SendRequest(readParams);
    3183            0 :     if (err != CHIP_NO_ERROR)
    3184              :     {
    3185            0 :         ChipLogError(Controller, "Failed to send read request: %" CHIP_ERROR_FORMAT, err.Format());
    3186            0 :         CommissioningStageComplete(err);
    3187            0 :         return;
    3188              :     }
    3189            0 :     mAttributeCache = std::move(attributeCache);
    3190            0 :     mReadClient     = std::move(readClient);
    3191            0 : }
    3192              : 
    3193            0 : void DeviceCommissioner::PerformCommissioningStep(DeviceProxy * proxy, CommissioningStage step, CommissioningParameters & params,
    3194              :                                                   CommissioningDelegate * delegate, EndpointId endpoint,
    3195              :                                                   Optional<System::Clock::Timeout> timeout)
    3196              : 
    3197              : {
    3198              :     MATTER_LOG_METRIC(kMetricDeviceCommissionerCommissionStage, step);
    3199              :     MATTER_LOG_METRIC_BEGIN(MetricKeyForCommissioningStage(step));
    3200              : 
    3201            0 :     if (params.GetCompletionStatus().err == CHIP_NO_ERROR)
    3202              :     {
    3203            0 :         ChipLogProgress(Controller, "Performing next commissioning step '%s'", StageToString(step));
    3204              :     }
    3205              :     else
    3206              :     {
    3207            0 :         ChipLogProgress(Controller, "Performing next commissioning step '%s' with completion status = '%s'", StageToString(step),
    3208              :                         params.GetCompletionStatus().err.AsString());
    3209              :     }
    3210              : 
    3211            0 :     if (mPairingDelegate)
    3212              :     {
    3213            0 :         mPairingDelegate->OnCommissioningStageStart(PeerId(GetCompressedFabricId(), proxy->GetDeviceId()), step);
    3214              :     }
    3215              : 
    3216            0 :     mCommissioningStepTimeout = timeout;
    3217            0 :     mCommissioningStage       = step;
    3218            0 :     mCommissioningDelegate    = delegate;
    3219            0 :     mDeviceBeingCommissioned  = proxy;
    3220              : 
    3221              :     // TODO: Extend timeouts to the DAC and Opcert requests.
    3222              :     // TODO(cecille): We probably want something better than this for breadcrumbs.
    3223            0 :     uint64_t breadcrumb = static_cast<uint64_t>(step);
    3224              : 
    3225            0 :     switch (step)
    3226              :     {
    3227            0 :     case CommissioningStage::kArmFailsafe: {
    3228            0 :         VerifyOrDie(endpoint == kRootEndpointId);
    3229              :         // Make sure the fail-safe value we set here actually ends up being used
    3230              :         // no matter what.
    3231            0 :         proxy->SetFailSafeExpirationTimestamp(System::Clock::kZero);
    3232            0 :         VerifyOrDie(ExtendArmFailSafeInternal(proxy, step, params.GetFailsafeTimerSeconds().ValueOr(kDefaultFailsafeTimeout),
    3233              :                                               timeout, OnArmFailSafe, OnBasicFailure, /* fireAndForget = */ false));
    3234              :     }
    3235            0 :     break;
    3236            0 :     case CommissioningStage::kReadCommissioningInfo: {
    3237            0 :         VerifyOrDie(endpoint == kRootEndpointId);
    3238            0 :         ChipLogProgress(Controller, "Sending read requests for commissioning information");
    3239              : 
    3240              :         // Allocate a ClusterStateCache to collect the data from our read requests.
    3241              :         // The cache will be released in:
    3242              :         // - SendCommissioningReadRequest when failing to send a read request.
    3243              :         // - FinishReadingCommissioningInfo when the ReadCommissioningInfo stage is completed.
    3244              :         // - CancelCommissioningInteractions
    3245            0 :         mAttributeCache = Platform::MakeUnique<app::ClusterStateCache>(*this);
    3246              : 
    3247              :         // Generally we need to make more than one read request, because as per spec a server only
    3248              :         // supports a limited number of paths per Read Interaction. Because the actual number of
    3249              :         // interactions we end up performing is dynamic, we track all of them within a single
    3250              :         // commissioning stage.
    3251            0 :         mReadCommissioningInfoProgress = 0;
    3252            0 :         ContinueReadingCommissioningInfo(params); // Note: assume params == delegate.GetCommissioningParameters()
    3253            0 :         break;
    3254              :     }
    3255            0 :     case CommissioningStage::kConfigureUTCTime: {
    3256            0 :         TimeSynchronization::Commands::SetUTCTime::Type request;
    3257            0 :         uint64_t kChipEpochUsSinceUnixEpoch = static_cast<uint64_t>(kChipEpochSecondsSinceUnixEpoch) * chip::kMicrosecondsPerSecond;
    3258              :         System::Clock::Microseconds64 utcTime;
    3259            0 :         if (System::SystemClock().GetClock_RealTime(utcTime) != CHIP_NO_ERROR || utcTime.count() <= kChipEpochUsSinceUnixEpoch)
    3260              :         {
    3261              :             // We have no time to give, but that's OK, just complete this stage
    3262            0 :             CommissioningStageComplete(CHIP_NO_ERROR);
    3263            0 :             return;
    3264              :         }
    3265              : 
    3266            0 :         request.UTCTime = utcTime.count() - kChipEpochUsSinceUnixEpoch;
    3267              :         // For now, we assume a seconds granularity
    3268            0 :         request.granularity = TimeSynchronization::GranularityEnum::kSecondsGranularity;
    3269            0 :         CHIP_ERROR err      = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnSetUTCError, endpoint, timeout);
    3270            0 :         if (err != CHIP_NO_ERROR)
    3271              :         {
    3272              :             // We won't get any async callbacks here, so just complete our stage.
    3273            0 :             ChipLogError(Controller, "Failed to send SetUTCTime command: %" CHIP_ERROR_FORMAT, err.Format());
    3274            0 :             CommissioningStageComplete(err);
    3275            0 :             return;
    3276              :         }
    3277            0 :         break;
    3278              :     }
    3279            0 :     case CommissioningStage::kConfigureTimeZone: {
    3280            0 :         if (!params.GetTimeZone().HasValue())
    3281              :         {
    3282            0 :             ChipLogError(Controller, "ConfigureTimeZone stage called with no time zone data");
    3283            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3284            0 :             return;
    3285              :         }
    3286            0 :         TimeSynchronization::Commands::SetTimeZone::Type request;
    3287            0 :         request.timeZone = params.GetTimeZone().Value();
    3288            0 :         CHIP_ERROR err   = SendCommissioningCommand(proxy, request, OnSetTimeZoneResponse, OnBasicFailure, endpoint, timeout);
    3289            0 :         if (err != CHIP_NO_ERROR)
    3290              :         {
    3291              :             // We won't get any async callbacks here, so just complete our stage.
    3292            0 :             ChipLogError(Controller, "Failed to send SetTimeZone command: %" CHIP_ERROR_FORMAT, err.Format());
    3293            0 :             CommissioningStageComplete(err);
    3294            0 :             return;
    3295              :         }
    3296            0 :         break;
    3297              :     }
    3298            0 :     case CommissioningStage::kConfigureDSTOffset: {
    3299            0 :         if (!params.GetDSTOffsets().HasValue())
    3300              :         {
    3301            0 :             ChipLogError(Controller, "ConfigureDSTOffset stage called with no DST data");
    3302            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3303            0 :             return;
    3304              :         }
    3305            0 :         TimeSynchronization::Commands::SetDSTOffset::Type request;
    3306            0 :         request.DSTOffset = params.GetDSTOffsets().Value();
    3307            0 :         CHIP_ERROR err    = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnBasicFailure, endpoint, timeout);
    3308            0 :         if (err != CHIP_NO_ERROR)
    3309              :         {
    3310              :             // We won't get any async callbacks here, so just complete our stage.
    3311            0 :             ChipLogError(Controller, "Failed to send SetDSTOffset command: %" CHIP_ERROR_FORMAT, err.Format());
    3312            0 :             CommissioningStageComplete(err);
    3313            0 :             return;
    3314              :         }
    3315            0 :         break;
    3316              :     }
    3317            0 :     case CommissioningStage::kConfigureDefaultNTP: {
    3318            0 :         if (!params.GetDefaultNTP().HasValue())
    3319              :         {
    3320            0 :             ChipLogError(Controller, "ConfigureDefaultNTP stage called with no default NTP data");
    3321            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3322            0 :             return;
    3323              :         }
    3324            0 :         TimeSynchronization::Commands::SetDefaultNTP::Type request;
    3325            0 :         request.defaultNTP = params.GetDefaultNTP().Value();
    3326            0 :         CHIP_ERROR err     = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnBasicFailure, endpoint, timeout);
    3327            0 :         if (err != CHIP_NO_ERROR)
    3328              :         {
    3329              :             // We won't get any async callbacks here, so just complete our stage.
    3330            0 :             ChipLogError(Controller, "Failed to send SetDefaultNTP command: %" CHIP_ERROR_FORMAT, err.Format());
    3331            0 :             CommissioningStageComplete(err);
    3332            0 :             return;
    3333              :         }
    3334            0 :         break;
    3335              :     }
    3336            0 :     case CommissioningStage::kScanNetworks: {
    3337            0 :         NetworkCommissioning::Commands::ScanNetworks::Type request;
    3338            0 :         if (params.GetWiFiCredentials().HasValue())
    3339              :         {
    3340            0 :             request.ssid.Emplace(params.GetWiFiCredentials().Value().ssid);
    3341              :         }
    3342            0 :         request.breadcrumb.Emplace(breadcrumb);
    3343            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnScanNetworksResponse, OnScanNetworksFailure, endpoint, timeout);
    3344            0 :         if (err != CHIP_NO_ERROR)
    3345              :         {
    3346              :             // We won't get any async callbacks here, so just complete our stage.
    3347            0 :             ChipLogError(Controller, "Failed to send ScanNetworks command: %" CHIP_ERROR_FORMAT, err.Format());
    3348            0 :             CommissioningStageComplete(err);
    3349            0 :             return;
    3350              :         }
    3351            0 :         break;
    3352              :     }
    3353            0 :     case CommissioningStage::kNeedsNetworkCreds: {
    3354              :         // Nothing to do.
    3355              :         //
    3356              :         // Either we did a scan and the OnScanNetworksSuccess and OnScanNetworksFailure
    3357              :         // callbacks will tell the DevicePairingDelegate that network credentials are
    3358              :         // needed, or we asked the DevicePairingDelegate for network credentials
    3359              :         // explicitly, and are waiting for it to get back to us.
    3360            0 :         break;
    3361              :     }
    3362            0 :     case CommissioningStage::kConfigRegulatory: {
    3363              :         // TODO(cecille): Worthwhile to keep this around as part of the class?
    3364              :         // TODO(cecille): Where is the country config actually set?
    3365            0 :         ChipLogProgress(Controller, "Setting Regulatory Config");
    3366              :         auto capability =
    3367            0 :             params.GetLocationCapability().ValueOr(app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum::kOutdoor);
    3368              :         app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum regulatoryConfig;
    3369              :         // Value is only switchable on the devices with indoor/outdoor capability
    3370            0 :         if (capability == app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum::kIndoorOutdoor)
    3371              :         {
    3372              :             // If the device supports indoor and outdoor configs, use the setting from the commissioner, otherwise fall back to
    3373              :             // the current device setting then to outdoor (most restrictive)
    3374            0 :             if (params.GetDeviceRegulatoryLocation().HasValue())
    3375              :             {
    3376            0 :                 regulatoryConfig = params.GetDeviceRegulatoryLocation().Value();
    3377            0 :                 ChipLogProgress(Controller, "Setting regulatory config to %u from commissioner override",
    3378              :                                 static_cast<uint8_t>(regulatoryConfig));
    3379              :             }
    3380            0 :             else if (params.GetDefaultRegulatoryLocation().HasValue())
    3381              :             {
    3382            0 :                 regulatoryConfig = params.GetDefaultRegulatoryLocation().Value();
    3383            0 :                 ChipLogProgress(Controller, "No regulatory config supplied by controller, leaving as device default (%u)",
    3384              :                                 static_cast<uint8_t>(regulatoryConfig));
    3385              :             }
    3386              :             else
    3387              :             {
    3388            0 :                 regulatoryConfig = app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum::kOutdoor;
    3389            0 :                 ChipLogProgress(Controller, "No overrride or device regulatory config supplied, setting to outdoor");
    3390              :             }
    3391              :         }
    3392              :         else
    3393              :         {
    3394            0 :             ChipLogProgress(Controller, "Device does not support configurable regulatory location");
    3395            0 :             regulatoryConfig = capability;
    3396              :         }
    3397              : 
    3398            0 :         CharSpan countryCode;
    3399            0 :         const auto & providedCountryCode = params.GetCountryCode();
    3400            0 :         if (providedCountryCode.HasValue())
    3401              :         {
    3402            0 :             countryCode = providedCountryCode.Value();
    3403              :         }
    3404              :         else
    3405              :         {
    3406              :             // Default to "XX", for lack of anything better.
    3407            0 :             countryCode = "XX"_span;
    3408              :         }
    3409              : 
    3410            0 :         GeneralCommissioning::Commands::SetRegulatoryConfig::Type request;
    3411            0 :         request.newRegulatoryConfig = regulatoryConfig;
    3412            0 :         request.countryCode         = countryCode;
    3413            0 :         request.breadcrumb          = breadcrumb;
    3414            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnSetRegulatoryConfigResponse, OnBasicFailure, endpoint, timeout);
    3415            0 :         if (err != CHIP_NO_ERROR)
    3416              :         {
    3417              :             // We won't get any async callbacks here, so just complete our stage.
    3418            0 :             ChipLogError(Controller, "Failed to send SetRegulatoryConfig command: %" CHIP_ERROR_FORMAT, err.Format());
    3419            0 :             CommissioningStageComplete(err);
    3420            0 :             return;
    3421              :         }
    3422              :     }
    3423            0 :     break;
    3424            0 :     case CommissioningStage::kConfigureTCAcknowledgments: {
    3425            0 :         ChipLogProgress(Controller, "Setting Terms and Conditions");
    3426              : 
    3427            0 :         if (!params.GetTermsAndConditionsAcknowledgement().HasValue())
    3428              :         {
    3429            0 :             ChipLogProgress(Controller, "Setting Terms and Conditions: Skipped");
    3430            0 :             CommissioningStageComplete(CHIP_NO_ERROR);
    3431            0 :             return;
    3432              :         }
    3433              : 
    3434            0 :         GeneralCommissioning::Commands::SetTCAcknowledgements::Type request;
    3435            0 :         TermsAndConditionsAcknowledgement termsAndConditionsAcknowledgement = params.GetTermsAndConditionsAcknowledgement().Value();
    3436            0 :         request.TCUserResponse = termsAndConditionsAcknowledgement.acceptedTermsAndConditions;
    3437            0 :         request.TCVersion      = termsAndConditionsAcknowledgement.acceptedTermsAndConditionsVersion;
    3438              : 
    3439            0 :         ChipLogProgress(Controller, "Setting Terms and Conditions: %hu, %hu", request.TCUserResponse, request.TCVersion);
    3440              :         CHIP_ERROR err =
    3441            0 :             SendCommissioningCommand(proxy, request, OnSetTCAcknowledgementsResponse, OnBasicFailure, endpoint, timeout);
    3442            0 :         if (err != CHIP_NO_ERROR)
    3443              :         {
    3444            0 :             ChipLogError(Controller, "Failed to send SetTCAcknowledgements command: %" CHIP_ERROR_FORMAT, err.Format());
    3445            0 :             CommissioningStageComplete(err);
    3446            0 :             return;
    3447              :         }
    3448            0 :         break;
    3449              :     }
    3450            0 :     case CommissioningStage::kSendPAICertificateRequest: {
    3451            0 :         ChipLogProgress(Controller, "Sending request for PAI certificate");
    3452            0 :         CHIP_ERROR err = SendCertificateChainRequestCommand(proxy, CertificateType::kPAI, timeout);
    3453            0 :         if (err != CHIP_NO_ERROR)
    3454              :         {
    3455              :             // We won't get any async callbacks here, so just complete our stage.
    3456            0 :             ChipLogError(Controller, "Failed to send CertificateChainRequest command to get PAI: %" CHIP_ERROR_FORMAT,
    3457              :                          err.Format());
    3458            0 :             CommissioningStageComplete(err);
    3459            0 :             return;
    3460              :         }
    3461            0 :         break;
    3462              :     }
    3463            0 :     case CommissioningStage::kSendDACCertificateRequest: {
    3464            0 :         ChipLogProgress(Controller, "Sending request for DAC certificate");
    3465            0 :         CHIP_ERROR err = SendCertificateChainRequestCommand(proxy, CertificateType::kDAC, timeout);
    3466            0 :         if (err != CHIP_NO_ERROR)
    3467              :         {
    3468              :             // We won't get any async callbacks here, so just complete our stage.
    3469            0 :             ChipLogError(Controller, "Failed to send CertificateChainRequest command to get DAC: %" CHIP_ERROR_FORMAT,
    3470              :                          err.Format());
    3471            0 :             CommissioningStageComplete(err);
    3472            0 :             return;
    3473              :         }
    3474            0 :         break;
    3475              :     }
    3476            0 :     case CommissioningStage::kSendAttestationRequest: {
    3477            0 :         ChipLogProgress(Controller, "Sending Attestation Request to the device.");
    3478            0 :         if (!params.GetAttestationNonce().HasValue())
    3479              :         {
    3480            0 :             ChipLogError(Controller, "No attestation nonce found");
    3481            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3482            0 :             return;
    3483              :         }
    3484            0 :         CHIP_ERROR err = SendAttestationRequestCommand(proxy, params.GetAttestationNonce().Value(), timeout);
    3485            0 :         if (err != CHIP_NO_ERROR)
    3486              :         {
    3487              :             // We won't get any async callbacks here, so just complete our stage.
    3488            0 :             ChipLogError(Controller, "Failed to send AttestationRequest command: %" CHIP_ERROR_FORMAT, err.Format());
    3489            0 :             CommissioningStageComplete(err);
    3490            0 :             return;
    3491              :         }
    3492            0 :         break;
    3493              :     }
    3494            0 :     case CommissioningStage::kAttestationVerification: {
    3495            0 :         ChipLogProgress(Controller, "Verifying Device Attestation information received from the device");
    3496            0 :         if (IsAttestationInformationMissing(params))
    3497              :         {
    3498            0 :             ChipLogError(Controller, "Missing attestation information");
    3499            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3500            0 :             return;
    3501              :         }
    3502              : 
    3503              :         DeviceAttestationVerifier::AttestationInfo info(
    3504            0 :             params.GetAttestationElements().Value(),
    3505            0 :             proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge(),
    3506            0 :             params.GetAttestationSignature().Value(), params.GetPAI().Value(), params.GetDAC().Value(),
    3507            0 :             params.GetAttestationNonce().Value(), params.GetRemoteVendorId().Value(), params.GetRemoteProductId().Value());
    3508              : 
    3509            0 :         CHIP_ERROR err = ValidateAttestationInfo(info);
    3510            0 :         if (err != CHIP_NO_ERROR)
    3511              :         {
    3512            0 :             ChipLogError(Controller, "Error validating attestation information: %" CHIP_ERROR_FORMAT, err.Format());
    3513            0 :             CommissioningStageComplete(CHIP_ERROR_FAILED_DEVICE_ATTESTATION);
    3514            0 :             return;
    3515              :         }
    3516              :     }
    3517            0 :     break;
    3518            0 :     case CommissioningStage::kAttestationRevocationCheck: {
    3519            0 :         ChipLogProgress(Controller, "Verifying the device's DAC chain revocation status");
    3520            0 :         if (IsAttestationInformationMissing(params))
    3521              :         {
    3522            0 :             ChipLogError(Controller, "Missing attestation information");
    3523            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3524            0 :             return;
    3525              :         }
    3526              : 
    3527              :         DeviceAttestationVerifier::AttestationInfo info(
    3528            0 :             params.GetAttestationElements().Value(),
    3529            0 :             proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge(),
    3530            0 :             params.GetAttestationSignature().Value(), params.GetPAI().Value(), params.GetDAC().Value(),
    3531            0 :             params.GetAttestationNonce().Value(), params.GetRemoteVendorId().Value(), params.GetRemoteProductId().Value());
    3532              : 
    3533            0 :         CHIP_ERROR err = CheckForRevokedDACChain(info);
    3534              : 
    3535            0 :         if (err != CHIP_NO_ERROR)
    3536              :         {
    3537            0 :             ChipLogError(Controller, "Error validating device's DAC chain revocation status: %" CHIP_ERROR_FORMAT, err.Format());
    3538            0 :             CommissioningStageComplete(CHIP_ERROR_FAILED_DEVICE_ATTESTATION);
    3539            0 :             return;
    3540              :         }
    3541              :     }
    3542            0 :     break;
    3543            0 :     case CommissioningStage::kJCMTrustVerification: {
    3544            0 :         CHIP_ERROR err = StartJCMTrustVerification(proxy);
    3545            0 :         if (err != CHIP_NO_ERROR)
    3546              :         {
    3547            0 :             ChipLogError(Controller, "Failed to start JCM Trust Verification: %" CHIP_ERROR_FORMAT, err.Format());
    3548            0 :             CommissioningStageComplete(err);
    3549            0 :             return;
    3550              :         }
    3551            0 :         break;
    3552              :     }
    3553              : 
    3554            0 :     case CommissioningStage::kSendOpCertSigningRequest: {
    3555            0 :         if (!params.GetCSRNonce().HasValue())
    3556              :         {
    3557            0 :             ChipLogError(Controller, "No CSR nonce found");
    3558            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3559            0 :             return;
    3560              :         }
    3561            0 :         CHIP_ERROR err = SendOperationalCertificateSigningRequestCommand(proxy, params.GetCSRNonce().Value(), timeout);
    3562            0 :         if (err != CHIP_NO_ERROR)
    3563              :         {
    3564              :             // We won't get any async callbacks here, so just complete our stage.
    3565            0 :             ChipLogError(Controller, "Failed to send CSR request: %" CHIP_ERROR_FORMAT, err.Format());
    3566            0 :             CommissioningStageComplete(err);
    3567            0 :             return;
    3568              :         }
    3569            0 :         break;
    3570              :     }
    3571            0 :     case CommissioningStage::kValidateCSR: {
    3572            0 :         if (!params.GetNOCChainGenerationParameters().HasValue() || !params.GetDAC().HasValue() || !params.GetCSRNonce().HasValue())
    3573              :         {
    3574            0 :             ChipLogError(Controller, "Unable to validate CSR");
    3575            0 :             return CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3576              :         }
    3577              :         // This is non-blocking, so send the callback immediately.
    3578            0 :         CHIP_ERROR err = ValidateCSR(proxy, params.GetNOCChainGenerationParameters().Value().nocsrElements,
    3579            0 :                                      params.GetNOCChainGenerationParameters().Value().signature, params.GetDAC().Value(),
    3580            0 :                                      params.GetCSRNonce().Value());
    3581            0 :         if (err != CHIP_NO_ERROR)
    3582              :         {
    3583            0 :             ChipLogError(Controller, "Failed to validate CSR: %" CHIP_ERROR_FORMAT, err.Format());
    3584              :         }
    3585            0 :         CommissioningStageComplete(err);
    3586            0 :         return;
    3587              :     }
    3588              :     break;
    3589            0 :     case CommissioningStage::kGenerateNOCChain: {
    3590            0 :         if (!params.GetNOCChainGenerationParameters().HasValue() || !params.GetDAC().HasValue() || !params.GetPAI().HasValue() ||
    3591            0 :             !params.GetCSRNonce().HasValue())
    3592              :         {
    3593            0 :             ChipLogError(Controller, "Unable to generate NOC chain parameters");
    3594            0 :             return CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3595              :         }
    3596            0 :         CHIP_ERROR err = ProcessCSR(proxy, params.GetNOCChainGenerationParameters().Value().nocsrElements,
    3597            0 :                                     params.GetNOCChainGenerationParameters().Value().signature, params.GetDAC().Value(),
    3598            0 :                                     params.GetPAI().Value(), params.GetCSRNonce().Value());
    3599            0 :         if (err != CHIP_NO_ERROR)
    3600              :         {
    3601            0 :             ChipLogError(Controller, "Failed to process Operational Certificate Signing Request (CSR): %" CHIP_ERROR_FORMAT,
    3602              :                          err.Format());
    3603            0 :             CommissioningStageComplete(err);
    3604            0 :             return;
    3605              :         }
    3606              :     }
    3607            0 :     break;
    3608            0 :     case CommissioningStage::kSendTrustedRootCert: {
    3609            0 :         if (!params.GetRootCert().HasValue() || !params.GetNoc().HasValue())
    3610              :         {
    3611            0 :             ChipLogError(Controller, "No trusted root cert or NOC specified");
    3612            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3613            0 :             return;
    3614              :         }
    3615            0 :         CHIP_ERROR err = SendTrustedRootCertificate(proxy, params.GetRootCert().Value(), timeout);
    3616            0 :         if (err != CHIP_NO_ERROR)
    3617              :         {
    3618            0 :             ChipLogError(Controller, "Error sending trusted root certificate: %" CHIP_ERROR_FORMAT, err.Format());
    3619            0 :             CommissioningStageComplete(err);
    3620            0 :             return;
    3621              :         }
    3622              : 
    3623            0 :         err = proxy->SetPeerId(params.GetRootCert().Value(), params.GetNoc().Value());
    3624            0 :         if (err != CHIP_NO_ERROR)
    3625              :         {
    3626            0 :             ChipLogError(Controller, "Error setting peer id: %" CHIP_ERROR_FORMAT, err.Format());
    3627            0 :             CommissioningStageComplete(err);
    3628            0 :             return;
    3629              :         }
    3630            0 :         if (!IsOperationalNodeId(proxy->GetDeviceId()))
    3631              :         {
    3632            0 :             ChipLogError(Controller, "Given node ID is not an operational node ID");
    3633            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3634            0 :             return;
    3635              :         }
    3636              :     }
    3637            0 :     break;
    3638            0 :     case CommissioningStage::kSendNOC: {
    3639            0 :         if (!params.GetNoc().HasValue() || !params.GetIpk().HasValue() || !params.GetAdminSubject().HasValue())
    3640              :         {
    3641            0 :             ChipLogError(Controller, "AddNOC contents not specified");
    3642            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3643            0 :             return;
    3644              :         }
    3645            0 :         CHIP_ERROR err = SendOperationalCertificate(proxy, params.GetNoc().Value(), params.GetIcac(), params.GetIpk().Value(),
    3646            0 :                                                     params.GetAdminSubject().Value(), timeout);
    3647            0 :         if (err != CHIP_NO_ERROR)
    3648              :         {
    3649              :             // We won't get any async callbacks here, so just complete our stage.
    3650            0 :             ChipLogError(Controller, "Error installing operational certificate with AddNOC: %" CHIP_ERROR_FORMAT, err.Format());
    3651            0 :             CommissioningStageComplete(err);
    3652            0 :             return;
    3653              :         }
    3654            0 :         break;
    3655              :     }
    3656            0 :     case CommissioningStage::kConfigureTrustedTimeSource: {
    3657            0 :         if (!params.GetTrustedTimeSource().HasValue())
    3658              :         {
    3659            0 :             ChipLogError(Controller, "ConfigureTrustedTimeSource stage called with no trusted time source data!");
    3660            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3661            0 :             return;
    3662              :         }
    3663            0 :         TimeSynchronization::Commands::SetTrustedTimeSource::Type request;
    3664            0 :         request.trustedTimeSource = params.GetTrustedTimeSource().Value();
    3665            0 :         CHIP_ERROR err            = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnBasicFailure, endpoint, timeout);
    3666            0 :         if (err != CHIP_NO_ERROR)
    3667              :         {
    3668              :             // We won't get any async callbacks here, so just complete our stage.
    3669            0 :             ChipLogError(Controller, "Failed to send SendTrustedTimeSource command: %" CHIP_ERROR_FORMAT, err.Format());
    3670            0 :             CommissioningStageComplete(err);
    3671            0 :             return;
    3672              :         }
    3673            0 :         break;
    3674              :     }
    3675            0 :     case CommissioningStage::kRequestWiFiCredentials: {
    3676            0 :         if (!mPairingDelegate)
    3677              :         {
    3678            0 :             ChipLogError(Controller, "Unable to request Wi-Fi credentials: no delegate available");
    3679            0 :             CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE);
    3680            0 :             return;
    3681              :         }
    3682              : 
    3683            0 :         CHIP_ERROR err = mPairingDelegate->WiFiCredentialsNeeded(endpoint);
    3684            0 :         CommissioningStageComplete(err);
    3685            0 :         return;
    3686              :     }
    3687            0 :     case CommissioningStage::kRequestThreadCredentials: {
    3688            0 :         if (!mPairingDelegate)
    3689              :         {
    3690            0 :             ChipLogError(Controller, "Unable to request Thread credentials: no delegate available");
    3691            0 :             CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE);
    3692            0 :             return;
    3693              :         }
    3694              : 
    3695            0 :         CHIP_ERROR err = mPairingDelegate->ThreadCredentialsNeeded(endpoint);
    3696            0 :         CommissioningStageComplete(err);
    3697            0 :         return;
    3698              :     }
    3699            0 :     case CommissioningStage::kWiFiNetworkSetup: {
    3700            0 :         if (!params.GetWiFiCredentials().HasValue())
    3701              :         {
    3702            0 :             ChipLogError(Controller, "No wifi credentials specified");
    3703            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3704            0 :             return;
    3705              :         }
    3706              : 
    3707            0 :         NetworkCommissioning::Commands::AddOrUpdateWiFiNetwork::Type request;
    3708            0 :         request.ssid        = params.GetWiFiCredentials().Value().ssid;
    3709            0 :         request.credentials = params.GetWiFiCredentials().Value().credentials;
    3710            0 :         request.breadcrumb.Emplace(breadcrumb);
    3711            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
    3712            0 :         if (err != CHIP_NO_ERROR)
    3713              :         {
    3714              :             // We won't get any async callbacks here, so just complete our stage.
    3715            0 :             ChipLogError(Controller, "Failed to send AddOrUpdateWiFiNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3716            0 :             CommissioningStageComplete(err);
    3717            0 :             return;
    3718              :         }
    3719              :     }
    3720            0 :     break;
    3721            0 :     case CommissioningStage::kThreadNetworkSetup: {
    3722            0 :         if (!params.GetThreadOperationalDataset().HasValue())
    3723              :         {
    3724            0 :             ChipLogError(Controller, "No thread credentials specified");
    3725            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3726            0 :             return;
    3727              :         }
    3728            0 :         NetworkCommissioning::Commands::AddOrUpdateThreadNetwork::Type request;
    3729            0 :         request.operationalDataset = params.GetThreadOperationalDataset().Value();
    3730            0 :         request.breadcrumb.Emplace(breadcrumb);
    3731            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
    3732            0 :         if (err != CHIP_NO_ERROR)
    3733              :         {
    3734              :             // We won't get any async callbacks here, so just complete our stage.
    3735            0 :             ChipLogError(Controller, "Failed to send AddOrUpdateThreadNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3736            0 :             CommissioningStageComplete(err);
    3737            0 :             return;
    3738              :         }
    3739              :     }
    3740            0 :     break;
    3741            0 :     case CommissioningStage::kFailsafeBeforeWiFiEnable:
    3742              :         FALLTHROUGH;
    3743              :     case CommissioningStage::kFailsafeBeforeThreadEnable:
    3744              :         // Before we try to do network enablement, make sure that our fail-safe
    3745              :         // is set far enough out that we can later try to do operational
    3746              :         // discovery without it timing out.
    3747            0 :         ExtendFailsafeBeforeNetworkEnable(proxy, params, step);
    3748            0 :         break;
    3749            0 :     case CommissioningStage::kWiFiNetworkEnable: {
    3750            0 :         if (!params.GetWiFiCredentials().HasValue())
    3751              :         {
    3752            0 :             ChipLogError(Controller, "No wifi credentials specified");
    3753            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3754            0 :             return;
    3755              :         }
    3756            0 :         NetworkCommissioning::Commands::ConnectNetwork::Type request;
    3757            0 :         request.networkID = params.GetWiFiCredentials().Value().ssid;
    3758            0 :         request.breadcrumb.Emplace(breadcrumb);
    3759              : 
    3760            0 :         CHIP_ERROR err = CHIP_NO_ERROR;
    3761            0 :         ChipLogProgress(Controller, "SendCommand kWiFiNetworkEnable, supportsConcurrentConnection=%s",
    3762              :                         params.GetSupportsConcurrentConnection().HasValue()
    3763              :                             ? (params.GetSupportsConcurrentConnection().Value() ? "true" : "false")
    3764              :                             : "missing");
    3765            0 :         err = SendCommissioningCommand(proxy, request, OnConnectNetworkResponse, OnBasicFailure, endpoint, timeout);
    3766              : 
    3767            0 :         if (err != CHIP_NO_ERROR)
    3768              :         {
    3769              :             // We won't get any async callbacks here, so just complete our stage.
    3770            0 :             ChipLogError(Controller, "Failed to send WiFi ConnectNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3771            0 :             CommissioningStageComplete(err);
    3772            0 :             return;
    3773              :         }
    3774              :     }
    3775            0 :     break;
    3776            0 :     case CommissioningStage::kThreadNetworkEnable: {
    3777            0 :         ByteSpan extendedPanId;
    3778            0 :         chip::Thread::OperationalDataset operationalDataset;
    3779            0 :         if (!params.GetThreadOperationalDataset().HasValue() ||
    3780            0 :             operationalDataset.Init(params.GetThreadOperationalDataset().Value()) != CHIP_NO_ERROR ||
    3781            0 :             operationalDataset.GetExtendedPanIdAsByteSpan(extendedPanId) != CHIP_NO_ERROR)
    3782              :         {
    3783            0 :             ChipLogError(Controller, "Invalid Thread operational dataset configured at commissioner!");
    3784            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3785            0 :             return;
    3786              :         }
    3787            0 :         NetworkCommissioning::Commands::ConnectNetwork::Type request;
    3788            0 :         request.networkID = extendedPanId;
    3789            0 :         request.breadcrumb.Emplace(breadcrumb);
    3790            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnConnectNetworkResponse, OnBasicFailure, endpoint, timeout);
    3791            0 :         if (err != CHIP_NO_ERROR)
    3792              :         {
    3793              :             // We won't get any async callbacks here, so just complete our stage.
    3794            0 :             ChipLogError(Controller, "Failed to send Thread ConnectNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3795            0 :             CommissioningStageComplete(err);
    3796            0 :             return;
    3797              :         }
    3798              :     }
    3799            0 :     break;
    3800            0 :     case CommissioningStage::kICDGetRegistrationInfo: {
    3801            0 :         GetPairingDelegate()->OnICDRegistrationInfoRequired();
    3802            0 :         return;
    3803              :     }
    3804              :     break;
    3805            0 :     case CommissioningStage::kICDRegistration: {
    3806            0 :         IcdManagement::Commands::RegisterClient::Type request;
    3807              : 
    3808            0 :         if (!(params.GetICDCheckInNodeId().HasValue() && params.GetICDMonitoredSubject().HasValue() &&
    3809            0 :               params.GetICDSymmetricKey().HasValue()))
    3810              :         {
    3811            0 :             ChipLogError(Controller, "No ICD Registration information provided!");
    3812            0 :             CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE);
    3813            0 :             return;
    3814              :         }
    3815              : 
    3816            0 :         request.checkInNodeID    = params.GetICDCheckInNodeId().Value();
    3817            0 :         request.monitoredSubject = params.GetICDMonitoredSubject().Value();
    3818            0 :         request.key              = params.GetICDSymmetricKey().Value();
    3819              : 
    3820              :         CHIP_ERROR err =
    3821            0 :             SendCommissioningCommand(proxy, request, OnICDManagementRegisterClientResponse, OnBasicFailure, endpoint, timeout);
    3822            0 :         if (err != CHIP_NO_ERROR)
    3823              :         {
    3824              :             // We won't get any async callbacks here, so just complete our stage.
    3825            0 :             ChipLogError(Controller, "Failed to send IcdManagement.RegisterClient command: %" CHIP_ERROR_FORMAT, err.Format());
    3826            0 :             CommissioningStageComplete(err);
    3827            0 :             return;
    3828              :         }
    3829              :     }
    3830            0 :     break;
    3831            0 :     case CommissioningStage::kEvictPreviousCaseSessions: {
    3832            0 :         auto scopedPeerId = GetPeerScopedId(proxy->GetDeviceId());
    3833              : 
    3834              :         // If we ever had a commissioned device with this node ID before, we may
    3835              :         // have stale sessions to it.  Make sure we don't re-use any of those,
    3836              :         // because clearly they are not related to this new device we are
    3837              :         // commissioning.  We only care about sessions we might reuse, so just
    3838              :         // clearing the ones associated with our fabric index is good enough and
    3839              :         // we don't need to worry about ExpireAllSessionsOnLogicalFabric.
    3840            0 :         mSystemState->SessionMgr()->ExpireAllSessions(scopedPeerId);
    3841              : #if CHIP_CONFIG_ENABLE_ADDRESS_RESOLVE_FALLBACK
    3842              :         Transport::Type type = proxy->GetSecureSession().Value()->AsSecureSession()->GetPeerAddress().GetTransportType();
    3843              :         // cache address if we are connected over TCP or UDP
    3844              :         if (type == Transport::Type::kTcp || type == Transport::Type::kUdp)
    3845              :         {
    3846              :             // Store the address we are using for PASE as a fallback for operational discovery
    3847              :             ResolveResult result;
    3848              :             result.address         = proxy->GetSecureSession().Value()->AsSecureSession()->GetPeerAddress();
    3849              :             result.mrpRemoteConfig = proxy->GetSecureSession().Value()->GetRemoteMRPConfig();
    3850              :             // Note: supportsTcpClient and supportsTcpServer are device capabilities from DNS-SD TXT records,
    3851              :             // not derivable from the transport type. They remain false (default) here.
    3852              :             // TODO: Consider passing these through RendezvousParameters if available from SetUpCodePairer.
    3853              :             mFallbackOperationalResolveResult.SetValue(result);
    3854              :         }
    3855              : #endif // CHIP_CONFIG_ENABLE_ADDRESS_RESOLVE_FALLBACK
    3856            0 :         CommissioningStageComplete(CHIP_NO_ERROR);
    3857            0 :         return;
    3858              :     }
    3859            0 :     case CommissioningStage::kFindOperationalForStayActive:
    3860              :     case CommissioningStage::kFindOperationalForCommissioningComplete: {
    3861              :         // If there is an error, CommissioningStageComplete will be called from OnDeviceConnectionFailureFn.
    3862            0 :         auto scopedPeerId = GetPeerScopedId(proxy->GetDeviceId());
    3863              :         MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissioningOperationalSetup);
    3864            0 :         mSystemState->CASESessionMgr()->FindOrEstablishSession(
    3865              :             scopedPeerId, &mOnDeviceConnectedCallback, &mOnDeviceConnectionFailureCallback,
    3866              : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    3867              :             /* attemptCount = */ 3, &mOnDeviceConnectionRetryCallback,
    3868              : #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    3869            0 :             TransportPayloadCapability::kMRPPayload, mFallbackOperationalResolveResult);
    3870              :     }
    3871            0 :     break;
    3872            0 :     case CommissioningStage::kPrimaryOperationalNetworkFailed: {
    3873              :         // nothing to do. This stage indicates that the primary operational network failed and the network config should be
    3874              :         // removed later.
    3875            0 :         break;
    3876              :     }
    3877            0 :     case CommissioningStage::kRemoveWiFiNetworkConfig: {
    3878            0 :         NetworkCommissioning::Commands::RemoveNetwork::Type request;
    3879            0 :         request.networkID = params.GetWiFiCredentials().Value().ssid;
    3880            0 :         request.breadcrumb.Emplace(breadcrumb);
    3881            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
    3882            0 :         if (err != CHIP_NO_ERROR)
    3883              :         {
    3884              :             // We won't get any async callbacks here, so just complete our stage.
    3885            0 :             ChipLogError(Controller, "Failed to send RemoveNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3886            0 :             CommissioningStageComplete(err);
    3887            0 :             return;
    3888              :         }
    3889            0 :         break;
    3890              :     }
    3891            0 :     case CommissioningStage::kRemoveThreadNetworkConfig: {
    3892            0 :         ByteSpan extendedPanId;
    3893            0 :         chip::Thread::OperationalDataset operationalDataset;
    3894            0 :         if (!params.GetThreadOperationalDataset().HasValue() ||
    3895            0 :             operationalDataset.Init(params.GetThreadOperationalDataset().Value()) != CHIP_NO_ERROR ||
    3896            0 :             operationalDataset.GetExtendedPanIdAsByteSpan(extendedPanId) != CHIP_NO_ERROR)
    3897              :         {
    3898            0 :             ChipLogError(Controller, "Invalid Thread operational dataset configured at commissioner!");
    3899            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3900            0 :             return;
    3901              :         }
    3902            0 :         NetworkCommissioning::Commands::RemoveNetwork::Type request;
    3903            0 :         request.networkID = extendedPanId;
    3904            0 :         request.breadcrumb.Emplace(breadcrumb);
    3905            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
    3906            0 :         if (err != CHIP_NO_ERROR)
    3907              :         {
    3908              :             // We won't get any async callbacks here, so just complete our stage.
    3909            0 :             ChipLogError(Controller, "Failed to send RemoveNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3910            0 :             CommissioningStageComplete(err);
    3911            0 :             return;
    3912              :         }
    3913            0 :         break;
    3914              :     }
    3915            0 :     case CommissioningStage::kICDSendStayActive: {
    3916            0 :         if (!(params.GetICDStayActiveDurationMsec().HasValue()))
    3917              :         {
    3918            0 :             ChipLogProgress(Controller, "Skipping kICDSendStayActive");
    3919            0 :             CommissioningStageComplete(CHIP_NO_ERROR);
    3920            0 :             return;
    3921              :         }
    3922              : 
    3923              :         // StayActive Command happens over CASE Connection
    3924            0 :         IcdManagement::Commands::StayActiveRequest::Type request;
    3925            0 :         request.stayActiveDuration = params.GetICDStayActiveDurationMsec().Value();
    3926            0 :         ChipLogError(Controller, "Send ICD StayActive with Duration %u", request.stayActiveDuration);
    3927              :         CHIP_ERROR err =
    3928            0 :             SendCommissioningCommand(proxy, request, OnICDManagementStayActiveResponse, OnBasicFailure, endpoint, timeout);
    3929            0 :         if (err != CHIP_NO_ERROR)
    3930              :         {
    3931              :             // We won't get any async callbacks here, so just complete our stage.
    3932            0 :             ChipLogError(Controller, "Failed to send IcdManagement.StayActive command: %" CHIP_ERROR_FORMAT, err.Format());
    3933            0 :             CommissioningStageComplete(err);
    3934            0 :             return;
    3935              :         }
    3936              :     }
    3937            0 :     break;
    3938            0 :     case CommissioningStage::kSendComplete: {
    3939              :         // CommissioningComplete command happens over the CASE connection.
    3940              :         GeneralCommissioning::Commands::CommissioningComplete::Type request;
    3941              :         CHIP_ERROR err =
    3942            0 :             SendCommissioningCommand(proxy, request, OnCommissioningCompleteResponse, OnBasicFailure, endpoint, timeout);
    3943            0 :         if (err != CHIP_NO_ERROR)
    3944              :         {
    3945              :             // We won't get any async callbacks here, so just complete our stage.
    3946            0 :             ChipLogError(Controller, "Failed to send CommissioningComplete command: %" CHIP_ERROR_FORMAT, err.Format());
    3947            0 :             CommissioningStageComplete(err);
    3948            0 :             return;
    3949              :         }
    3950              :     }
    3951            0 :     break;
    3952              : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
    3953              :     case CommissioningStage::kUnpoweredPhaseComplete:
    3954              :         ChipLogProgress(Controller, "Completed unpowered commissioning phase, marking commissioning as complete");
    3955              :         CommissioningStageComplete(CHIP_NO_ERROR);
    3956              :         break;
    3957              : #endif
    3958            0 :     case CommissioningStage::kCleanup:
    3959            0 :         CleanupCommissioning(proxy, proxy->GetDeviceId(), params.GetCompletionStatus());
    3960            0 :         break;
    3961            0 :     case CommissioningStage::kError:
    3962            0 :         mCommissioningStage = CommissioningStage::kSecurePairing;
    3963            0 :         break;
    3964            0 :     case CommissioningStage::kSecurePairing:
    3965            0 :         break;
    3966              :     }
    3967              : }
    3968              : 
    3969            0 : void DeviceCommissioner::ExtendFailsafeBeforeNetworkEnable(DeviceProxy * device, CommissioningParameters & params,
    3970              :                                                            CommissioningStage step)
    3971              : {
    3972            0 :     auto * commissioneeDevice = FindCommissioneeDevice(device->GetDeviceId());
    3973            0 :     if (device != commissioneeDevice)
    3974              :     {
    3975              :         // Not a commissionee device; just return.
    3976            0 :         ChipLogError(Controller, "Trying to extend fail-safe for an unknown commissionee with device id " ChipLogFormatX64,
    3977              :                      ChipLogValueX64(device->GetDeviceId()));
    3978            0 :         CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE, CommissioningDelegate::CommissioningReport());
    3979            0 :         return;
    3980              :     }
    3981              : 
    3982              :     // Try to make sure we have at least enough time for our expected
    3983              :     // commissioning bits plus the MRP retries for a Sigma1.
    3984            0 :     uint16_t failSafeTimeoutSecs = params.GetFailsafeTimerSeconds().ValueOr(kDefaultFailsafeTimeout);
    3985            0 :     auto sigma1Timeout           = CASESession::ComputeSigma1ResponseTimeout(commissioneeDevice->GetPairing().GetRemoteMRPConfig());
    3986            0 :     uint16_t sigma1TimeoutSecs   = std::chrono::duration_cast<System::Clock::Seconds16>(sigma1Timeout).count();
    3987            0 :     if (UINT16_MAX - failSafeTimeoutSecs < sigma1TimeoutSecs)
    3988              :     {
    3989            0 :         failSafeTimeoutSecs = UINT16_MAX;
    3990              :     }
    3991              :     else
    3992              :     {
    3993            0 :         failSafeTimeoutSecs = static_cast<uint16_t>(failSafeTimeoutSecs + sigma1TimeoutSecs);
    3994              :     }
    3995              : 
    3996            0 :     if (!ExtendArmFailSafeInternal(commissioneeDevice, step, failSafeTimeoutSecs, MakeOptional(kMinimumCommissioningStepTimeout),
    3997              :                                    OnArmFailSafe, OnBasicFailure, /* fireAndForget = */ false))
    3998              :     {
    3999              :         // A false return is fine; we don't want to make the fail-safe shorter here.
    4000            0 :         CommissioningStageComplete(CHIP_NO_ERROR, CommissioningDelegate::CommissioningReport());
    4001              :     }
    4002              : }
    4003              : 
    4004            0 : bool DeviceCommissioner::IsAttestationInformationMissing(const CommissioningParameters & params)
    4005              : {
    4006            0 :     if (!params.GetAttestationElements().HasValue() || !params.GetAttestationSignature().HasValue() ||
    4007            0 :         !params.GetAttestationNonce().HasValue() || !params.GetDAC().HasValue() || !params.GetPAI().HasValue() ||
    4008            0 :         !params.GetRemoteVendorId().HasValue() || !params.GetRemoteProductId().HasValue())
    4009              :     {
    4010            0 :         return true;
    4011              :     }
    4012              : 
    4013            0 :     return false;
    4014              : }
    4015              : 
    4016            0 : CHIP_ERROR DeviceController::GetCompressedFabricIdBytes(MutableByteSpan & outBytes) const
    4017              : {
    4018            0 :     const auto * fabricInfo = GetFabricInfo();
    4019            0 :     VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX);
    4020            0 :     return fabricInfo->GetCompressedFabricIdBytes(outBytes);
    4021              : }
    4022              : 
    4023            0 : CHIP_ERROR DeviceController::GetRootPublicKey(Crypto::P256PublicKey & outRootPublicKey) const
    4024              : {
    4025            0 :     const auto * fabricTable = GetFabricTable();
    4026            0 :     VerifyOrReturnError(fabricTable != nullptr, CHIP_ERROR_INCORRECT_STATE);
    4027            0 :     return fabricTable->FetchRootPubkey(mFabricIndex, outRootPublicKey);
    4028              : }
    4029              : 
    4030            0 : bool DeviceCommissioner::HasValidCommissioningMode(const Dnssd::CommissionNodeData & nodeData)
    4031              : {
    4032            0 :     if (nodeData.commissioningMode == to_underlying(Dnssd::CommissioningMode::kDisabled))
    4033              :     {
    4034            0 :         ChipLogProgress(Controller, "Discovered device does not have an open commissioning window.");
    4035            0 :         return false;
    4036              :     }
    4037            0 :     return true;
    4038              : }
    4039              : 
    4040              : } // namespace Controller
    4041              : } // namespace chip
        

Generated by: LCOV version 2.0-1