<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _set_chain_sid(chain_model, sid):
 """Set or update SID for chain. If the chain already has a SID, ``sid`` must either be None or match the existing SID. """

    if not sid:
        return
    if chain_model.sid and chain_model.sid.did != sid:
        raise d1_common.types.exceptions.ServiceFailure(
            0,
            'Attempted to modify existing SID. '
            'existing_sid="{}", new_sid="{}"'.format(chain_model.sid.did, sid),
        )
    chain_model.sid = d1_gmn.app.did.get_or_create_did(sid)
    chain_model.save()