<a id="tor-spec.txt-5.5"></a>

# Routing relay cells{#routing-relay-cells}

<a id="tor-spec.txt-5.5.1"></a>

## Circuit ID Checks

When a node wants to send a RELAY or RELAY_EARLY cell, it checks the cell's
circID and determines whether the corresponding circuit along that
connection is still open. If not, the node drops the cell.

When a node receives a RELAY or RELAY_EARLY cell, it checks the cell's
circID and determines whether it has a corresponding circuit along
that connection. If not, the node drops the cell.

> Here and elsewhere, we refer to RELAY and RELAY_EARLY cells
> collectively as "relay cells".

<a id="tor-spec.txt-5.5.2"></a>

## Forward Direction

The forward direction is the direction that CREATE/CREATE2 cells
are sent.

<a id="tor-spec.txt-5.5.2.1"></a>

### Routing from the Origin

When a relay cell is sent from an OP, the OP encrypts the cell's body
with the stream cipher as follows:

```text
OP sends relay cell:
   For I=N...1, where N is the destination node:
      Encrypt with Kf_I.
   Transmit the encrypted cell to node 1.
```

<a id="tor-spec.txt-5.5.2.2"></a>

### Relaying Forward at Onion Routers

When a forward relay cell is received by an OR, it decrypts the cell's body
with the stream cipher, as follows:

```text
'Forward' relay cell:
   Use Kf as key; decrypt.
```

The OR then decides whether it recognizes the relay cell, by
inspecting the cell as described in [Relay cells](./relay-cells.md#relay-cells).  If the OR
recognizes the cell, it processes the contents of the relay cell.
Otherwise, it passes the decrypted relay cell along the circuit if
the circuit continues.  If the OR at the end of the circuit
encounters an unrecognized relay cell, an error has occurred: the OR
sends a DESTROY cell to tear down the circuit.

For more information, see
[Application connections and stream management](./streams.md#application-connections-and-stream-management).

<a id="tor-spec.txt-5.5.3"></a>

## Backward Direction

The backward direction is the opposite direction from
CREATE/CREATE2 cells.

<a id="tor-spec.txt-5.5.3.1"></a>

### Relaying Backward at Onion Routers

When a backward relay cell is received by an OR, it encrypts the cell's body
with the stream cipher, as follows:

```text
'Backward' relay cell:
   Use Kb as key; encrypt.
```

<a id="tor-spec.txt-5.5.3"></a>

## Routing to the Origin

When a relay cell arrives at an OP, the OP decrypts the cell's body
with the stream cipher as follows:

```text
OP receives relay cell from node 1:
   For I=1...N, where N is the final node on the circuit:
       Decrypt with Kb_I.
       If the cell is recognized (see [1]), then:
           The sending node is I.
           Stop and process the cell.
```

\[1\]: ["Relay cells"](./relay-cells.md#relay-cells)
