\chapter{Codice script MotoController}
\label{controller}
\thispagestyle{empty}

\begin{lstlisting}
using UnityEngine;
using SerialLibrary;
using System.Threading;
using System.IO;

public class MotoController : MonoBehaviour {

    private SerialLibrary.DataReceiver receiver;
    private float pedalata;
    private float deltaTimePedalata;

    public string PortName = "COM5";

    public float deltaTimeSoglia = 0.71f;
    public float maxSpeedPedalata = 50.0f;

    private Rigidbody rigid;

    public WheelCollider FrontWheelCollider;
    public WheelCollider RearWheelCollider;
    public Transform FrontWheelTransform;
    public Transform RearWheelTransform;
	public Transform SteeringHandlebar;
    public Transform Centro;

    //Bike Body Lean
    public GameObject body;
    public float bodyVerticalLean = 10.0f;
    public float bodyHorizontalLean = 10.0f;
    private float horizontalLean = 0.0f;
    private float verticalLean = 0.0f;

    //Configurations
    public float EngineTorque = 1500f;

	[HideInInspector]
    public float SteerAngle = 30f;
    public float Speed;
    public float highSpeedSteerAngle = 40f;
    public float highSpeedSteerAngleAtSpeed = 80f;
    public float maxSpeed = 180f;
    public float Brake = 2500f;
    public float friction = 6f;

    private float motorInput = 0f;
    private float defsteerAngle = 0f;
    private float RotationValue1 = 0f;
    private float RotationValue2 = 0f;

	[HideInInspector]
    public float steerInput = 0f;
    private bool reversing = false;
    private float sterzata;
    private int lastInputSterzata;
    private float lastSterzata;
    private Vector3 euler;
    private Vector3 FrontEuler;
    private Thread thread;

    void Start() {
        //Rigidbody
        rigid = GetComponent<Rigidbody>();
        rigid.constraints = RigidbodyConstraints.FreezeRotationZ;
        rigid.centerOfMass = new Vector3(Centro.localPosition.x * transform.localScale.x, Centro.localPosition.y * transform.localScale.y, Centro.localPosition.z * transform.localScale.z);
        rigid.maxAngularVelocity = 2f;

        defsteerAngle = SteerAngle;
        lastInputSterzata = 7;

        receiver = new DataReceiver(PortName);
        receiver.PedalataTrovata += Receiver_PedalataTrovata;
        thread = new Thread(receiver.start);

        euler = SteeringHandlebar.localEulerAngles;
        FrontEuler = FrontWheelTransform.localEulerAngles;

        thread.Start();
    }

    private void Receiver_PedalataTrovata(int inputSterzo, float inputPedalata)
    {
        if (lastInputSterzata == 0 && inputSterzo == 15)
            inputSterzo = 0;

        pedalata = inputPedalata/maxSpeedPedalata;

        sterzata = (inputSterzo - 7.0f) / 8; // Mathf.Lerp(lastSterzata, (inputSterzo - 7.0f) / 8, 0.2f);

        lastInputSterzata = inputSterzo;
        lastSterzata = sterzata;
    }

    void FixedUpdate()
    {
        Inputs();
        Engine();
        Braking();
    }

    void Update()
    {
        WheelAlign();
        Lean();
    }

    void Inputs()
    {
        Speed = rigid.velocity.magnitude * 3.6f;

        transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, 0);

        motorInput = pedalata + Input.GetAxis("Vertical");
        steerInput = sterzata + Input.GetAxis("Horizontal");

        if (motorInput < 0)
            reversing = true;
        else
            reversing = false;

    }

    void Engine()
    {
        FrontWheelCollider.steerAngle = SteerAngle * steerInput;

        if (Speed > maxSpeed)
        {
            RearWheelCollider.motorTorque = 0;
        }
        else if (!reversing)
        {
            RearWheelCollider.motorTorque = EngineTorque * Mathf.Clamp(motorInput, 0f, 1f);
        }

        if (reversing)
        {
            if (Speed < maxSpeed)//test con 10
            {
                RearWheelCollider.motorTorque = (EngineTorque * motorInput) / 5f;
            }
            else
            {
                RearWheelCollider.motorTorque = 0;
            }
        }

    }

    public void Braking()
    {
        // Deceleration.
        if (Mathf.Abs(pedalata) <= .05f)
        {
            FrontWheelCollider.brakeTorque = (Brake) / friction; // 25f;
            RearWheelCollider.brakeTorque = (Brake) / friction; // 25f;
        }
        else if (motorInput < 0 && !reversing)
        {
            FrontWheelCollider.brakeTorque = (Brake) * (Mathf.Abs(motorInput) / 5f);
            RearWheelCollider.brakeTorque = (Brake) * (Mathf.Abs(motorInput));
        }
        else
        {
            FrontWheelCollider.brakeTorque = 0;
            RearWheelCollider.brakeTorque = 0;
        }

    }

    void WheelAlign()
    {
        RaycastHit hit;
        WheelHit CorrespondingGroundHit;
        float extension_F;
        float extension_R;

        Vector3 ColliderCenterPointFL = FrontWheelCollider.transform.TransformPoint(FrontWheelCollider.center);
        FrontWheelCollider.GetGroundHit(out CorrespondingGroundHit);

        if (Physics.Raycast(ColliderCenterPointFL, -FrontWheelCollider.transform.up, out hit, (FrontWheelCollider.suspensionDistance + FrontWheelCollider.radius) * transform.localScale.y))
        {
            if (hit.transform.gameObject.layer != LayerMask.NameToLayer("Bici"))
            {
                FrontWheelTransform.transform.position = hit.point + (FrontWheelCollider.transform.up * FrontWheelCollider.radius) * transform.localScale.y;
                extension_F = (
                -FrontWheelCollider.transform.InverseTransformPoint(
                CorrespondingGroundHit.point).y - FrontWheelCollider.radius) / FrontWheelCollider.suspensionDistance;
			}
        }
        else
        {
            FrontWheelTransform.transform.position = ColliderCenterPointFL - (FrontWheelCollider.transform.up * FrontWheelCollider.suspensionDistance) * transform.localScale.y;
        }
        //rotazione ruota anteriore: x fissa, y data dal movimento, z data dal perno
        RotationValue1 += FrontWheelCollider.rpm * (6) * Time.deltaTime;
        FrontEuler.x = 0;
        FrontEuler.y = -RotationValue1;
        FrontWheelTransform.localEulerAngles = FrontEuler;

        Vector3 ColliderCenterPointRL = RearWheelCollider.transform.TransformPoint(RearWheelCollider.center);
        RearWheelCollider.GetGroundHit(out CorrespondingGroundHit);

        if (Physics.Raycast(ColliderCenterPointRL, -RearWheelCollider.transform.up, out hit, (RearWheelCollider.suspensionDistance + RearWheelCollider.radius) * transform.localScale.y))
        {
            if (hit.transform.gameObject.layer != LayerMask.NameToLayer("Bici"))
            {
                RearWheelTransform.transform.position = hit.point + (RearWheelCollider.transform.up * RearWheelCollider.radius) * transform.localScale.y;
                extension_R = (
                -RearWheelCollider.transform.InverseTransformPoint(
                CorrespondingGroundHit.point).y - RearWheelCollider.radius) / RearWheelCollider.suspensionDistance;
			}
        }
        else
        {
            RearWheelTransform.transform.position = ColliderCenterPointRL - (RearWheelCollider.transform.up * RearWheelCollider.suspensionDistance) * transform.localScale.y;
        }
        RotationValue2 += RearWheelCollider.rpm * (6) * Time.deltaTime;
        RearWheelTransform.transform.rotation = RearWheelCollider.transform.rotation * Quaternion.Euler(RotationValue2, RearWheelCollider.steerAngle, RearWheelCollider.transform.rotation.z+90);

        //rotazione del manubrio
		if (SteeringHandlebar) {
            //ottengo la differenza di angolo tra la posizione corrente (euler.z) e l'angolo della wheelcollider
            float angleDifference = euler.z - FrontWheelCollider.steerAngle;

            euler.z = (euler.z - angleDifference) % 360; //applico la differenza
            SteeringHandlebar.localEulerAngles = euler;  // aggiorno la rotazione
        }
    }

    void Lean()
    {
        verticalLean = Mathf.Clamp(Mathf.Lerp(verticalLean, transform.InverseTransformDirection(rigid.angularVelocity).x * bodyVerticalLean, Time.deltaTime * 5f), -10.0f, 10.0f);

        WheelHit CorrespondingGroundHit;
        FrontWheelCollider.GetGroundHit(out CorrespondingGroundHit);

        float normalizedLeanAngle = Mathf.Clamp(CorrespondingGroundHit.sidewaysSlip, -1f, 1f);

        if (transform.InverseTransformDirection(rigid.velocity).z > 0f)
            normalizedLeanAngle = -1;
        else
            normalizedLeanAngle = 1;

        horizontalLean = Mathf.Clamp(Mathf.Lerp(horizontalLean, (transform.InverseTransformDirection(rigid.angularVelocity).y * normalizedLeanAngle) * bodyHorizontalLean, Time.deltaTime * 3f), -50.0f, 50.0f);

        Quaternion target = Quaternion.Euler(verticalLean, body.transform.localRotation.y + (rigid.angularVelocity.z), horizontalLean);
        body.transform.localRotation = target;

        rigid.centerOfMass = new Vector3((Centro.localPosition.x) * transform.localScale.x, (Centro.localPosition.y) * transform.localScale.y, (Centro.localPosition.z) * transform.localScale.z);
    }

    void OnApplicationQuit()
    {
        receiver.stop();
        thread.Join();
        Debug.Log("Chiusura del programma: " + (thread.ThreadState));
    }

    public static void msgToDebug(string txt)
    {
        Debug.Log(txt);
 	}
}
\end{lstlisting}


\section{Axe Training}\label{perk:axeTraining}
\textbf{Cost:} 200CP\\
\textbf{Requirements:} Simple Weapon Training\\
\textbf{Passive, Repeatable, Source(200 Gold)}\\
You are trained with axes.
This includes all weapons with the "Axe" descriptor.
You add your level to attack and block rolls made with these weapons.\\
If you already have another perk that grants you proficiency with a certain weapon, only the one with the highest bonus counts.\\
\\
Level Progression:\\
\\
\rowcolors{2}{lightgray}{white}
\begin{tabular}{l | l | l | l}
	Level & CP Cost & Gold Cost & Effect\\
	II & 800CP & 800 Gold & You also add 1d4 to attack and block rolls.\\
	III & 4,500CP & 4,500 Gold & You also add 2d4 to attack and block rolls.\\
	IV & 12,500CP & 12,500 Gold & You also add 3d4 to attack and block rolls.\\
\end{tabular}


\chapter{Weapons}\label{ch:weapons}
These are weapons that can be bought, their descriptors, their reach, the abilities that can be used for their attack and block rolls, their attack and block actions themselves and their weight and price.\\
\section{Description}\label{sec:weaponDescription}
\subsection{Weapon quality}\label{subsec:weaponQuality}
Manufactured weapons can have different qualities.
For example, a dagger might be rusted or a longsword might be masterfully crafted.
The quality of a weapon changes its damage - this modifier ranges from --3 (broken) to +3 (high mastery craftsmanship).
The quality of a weapon changes its base price:\\

\begin{itemize}
    \item -3: Base Price * 1/4
    \item -2: Base Price * 1/2
    \item -1: Base Price * 3/4
    \item 0: Base Price
    \item +1: Base Price * 1.5
    \item +2: Base Price * 2
    \item +3: Base Price * 3
\end{itemize}

\subsection{Multiple Damage Types}\label{subsec:multipleDamageTypeWeapons}
Some weapons, like the~\nameref{weapon:mace} have attacks that deal multiple damage types.
Whenever a wielder of such a weapon gains a bonus to weapon damage (from high quality, a race like~\nameref{race:daevana} or a perk like~\nameref{maneuver:brutalAttack}), they can choose which damage type to apply each modifier to.

\subsection{Draw/Sheath Weapons}\label{subsec:sheathWeapons}
Most weapons have a sheath/unsheath action.
This action denotes how many AP it cost to draw and sheath a weapon.
Sheathing or drawing a weapon can be done as part of another action, such as an attack.\\
A weapon that does not have a draw/sheath action is considered to be non-sheathable, meaning it has to be carried around in some other way.

\subsection{Scabbards and straps}\label{subsec:scabbards}
In order to carry a weapon sheathed, a character must affix a scabbard or holding strap to their back or belt.
When buying a weapon, this container is considered to be part of the base price.\\
If a weapon can not be sheathed, it is assumed that it does not have a scabbard or holding strap.

\section{Weapon List}\label{sec:weaponList}
\subsection{Simple Weapons}\label{subsec:simpleWeapons}

\input{./items/equipment/weapons/simple/club.tex}

\input{./items/equipment/weapons/simple/dagger.tex}

\input{./items/equipment/weapons/simple/greatclub.tex}

\input{./items/equipment/weapons/simple/handaxe.tex}

\input{./items/equipment/weapons/simple/lightcrossbow.tex}

\input{./items/equipment/weapons/simple/lighthammer.tex}

\input{./items/equipment/weapons/simple/pike.tex}

\input{./items/equipment/weapons/simple/quarterstaff.tex}

\input{./items/equipment/weapons/simple/shortspear.tex}

\input{./items/equipment/weapons/simple/shortsword.tex}

\input{./items/equipment/weapons/simple/sling.tex}

\input{./items/equipment/weapons/simple/slingshot.tex}

\input{./items/equipment/weapons/simple/spear.tex}

\input{./items/equipment/weapons/simple/throwingstones.tex}

\input{./items/equipment/weapons/simple/unarmed.tex}

\subsection{Regular Weapons}\label{subsec:regularWeapons}

\input{./items/equipment/weapons/regular/armingsword.tex}

\input{./items/equipment/weapons/regular/battleaxe.tex}

\input{./items/equipment/weapons/regular/beardedaxe.tex}

\input{./items/equipment/weapons/regular/bow.tex}

\input{./items/equipment/weapons/regular/broadsword.tex}

\input{./items/equipment/weapons/regular/glaive.tex}

\input{./items/equipment/weapons/regular/greataxe.tex}

\input{./items/equipment/weapons/regular/greatsword.tex}

\input{./items/equipment/weapons/regular/halberd.tex}

\input{./items/equipment/weapons/regular/heavycrossbow.tex}

\input{./items/equipment/weapons/regular/lance.tex}

\input{./items/equipment/weapons/regular/longbow.tex}

\input{./items/equipment/weapons/regular/longsword.tex}

\input{./items/equipment/weapons/regular/mace.tex}

\input{./items/equipment/weapons/regular/maul.tex}

\input{./items/equipment/weapons/regular/morningstar.tex}

\input{./items/equipment/weapons/regular/rapier.tex}

\input{./items/equipment/weapons/regular/ridingbow.tex}

\input{./items/equipment/weapons/regular/warhammer.tex}

\subsection{Unusual Weapons}\label{subsec:unusualWeapons}

\input{./items/equipment/weapons/unusual/guisarme.tex}

\input{./items/equipment/weapons/unusual/handcrossbow.tex}

\input{./items/equipment/weapons/unusual/pistol.tex}

\input{./items/equipment/weapons/unusual/revolver.tex}

\input{./items/equipment/weapons/unusual/rifle.tex}

\subsection{Shields}\label{subsec:shields}

\input{./items/equipment/weapons/shields/buckler.tex}

\input{./items/equipment/weapons/shields/crestshield.tex}

\input{./items/equipment/weapons/shields/kiteshield.tex}

\input{./items/equipment/weapons/shields/roundshield.tex}

\input{./items/equipment/weapons/shields/towershield.tex}

% \subsection{Siege Weapons}\label{subsec:siegeWeapons}

% \include{./items/equipment/weapons/siege/ballista}
% \include{./items/equipment/weapons/siege/scorpion}


\subsection{Forum}
\label{sec:forum}
\label{sec:hasModerator}

A \tForum is a meeting point where people post \tMessages.
There exists three categories of \tForums:
Wall ($\eForum_\textsf{w}$),
Album ($\eForum_\textsf{a}$),
and Group ($\eForum_\textsf{g}$).
Each \tForum has a set of \tPersons connected via \tHasMember edges, a set of \tTags connected via \tHasTag edges, a single moderator connected by a \tHasModerator edge and a set of \tMessages (discussed in Section \ref{sec:message}).
For all \tForums the outgoing \tHasTag edges get their creation date and deletion date from $\varc{\eForum}$ and $\vard{\eForum}$, respectively.

\subsubsection{Groups}
Groups are public places for people that share interests, any \tPerson can create a Group $\eForum_\textsf{g}$ during their lifespan. A Group can be deleted anytime after it was created.
\begin{itemize}
    \item $\varc{\eForum}_{\mathsf{g}} \in \interval{\varc{\ePerson} + \Delta}{\min (\vard{\ePerson}, \xSE)}$
    \item $\vard{\eForum}_{\mathsf{g}} \in \interval{\varc{\eForum}_{\mathsf{g}} + \Delta}{\xNC}$
\end{itemize}

\paragraph{Group Moderator}
The initial \tHasModerator $\eHasModerator_{\mathsf{g}}$ is the Group creator. If the moderator leaves the Group, the Group will have no moderator (this is allowed in the schema of version 0.4.0+, see \autoref{fig:schema}).
\begin{itemize}
\item $\varc{\eHasModerator}_{\mathsf{g}} \in \interval{\varc{\eForum}_{\mathsf{g}} + \Delta}{\min (\vard{\eForum}_{\mathsf{g}}, \vard{\ePerson}, \xSE)}$
\item $\vard{\eHasModerator}_{\mathsf{g}} \in \interval{ \varc{\eHasModerator}_{\mathsf{g}} + \Delta}{\min (\vard{\eForum}_{\mathsf{g}}, \vard{\ePerson})}$
\end{itemize}

\paragraph{Group Membership}
Any \tPerson $\ePerson$ can become a member of a given group. The \tHasMember $\eHasMember_{\mathsf{g}}$ creation is generated from the interval in which the \tPerson and \tForum lifespans overlap. The deletion date is generated from the interval between the membership creation date (incremented by $\Delta$) and the minimum of the \tPerson and \tForum deletion dates.
\begin{itemize}
    \item $\varc{\eHasMember}_{\mathsf{g}} \in \interval{\max ( \varc{\eForum}_{\mathsf{g}}, \varc{\ePerson}) + \Delta}{\min (\vard{\eForum}, \vard{\ePerson}, \xSE)} $
    \item $\vard{\eHasMember}_{\mathsf{g}} \in \interval{\varc{\eHasMember}_{\mathsf{g}} + \Delta}{\min (\vard{\eForum}_{\mathsf{g}}, \vard{\ePerson})}$
\end{itemize}

\subsubsection{Walls}
Every \tPerson $\ePerson$, has a Wall $\eForum_\textsf{w}$ which is created when the \tPerson joins the social network. The wall is deleted when the \tPerson is deleted.
\begin{itemize}
    \item $\varc{\eForum}_{\mathsf{w}} = \varc{\ePerson} + \Delta$
    \item $\vard{\eForum}_{\mathsf{w}} = \vard{\ePerson}$
\end{itemize}

\paragraph{Wall Moderator}
Each \tPerson has a \tHasModerator $\eHasModerator_{\mathsf{w}}$ edge to their wall, which gets the creation date (incremented by $\Delta$) and deletion date from $\eForum_\textsf{w}$.
Note, only the moderator can create \tPost nodes on the wall and the connecting \tTag nodes are set based on the interest of the moderator.
\begin{itemize}
    \item $\varc{\eHasModerator}_{\mathsf{w}} = \varc{\eForum}_{\mathsf{w}} + \Delta$
    \item $\vard{\eHasModerator}_{\mathsf{w}} = \vard{\eForum}_{\mathsf{w}}$
\end{itemize}

\paragraph{Wall Membership}
For a \tPerson $p_i$, all their friends $p_j$ (\tPerson nodes connected via a \tKnows edge) become members of $\eForum_\textsf{w}$ at the time the \tKnows edge is created. Hence, a \tHasMember $\eHasMember_{\mathsf{w}}$ edge gets the creation date of \tKnows incremented by $\Delta$. The deletion date is derived from the minimum of the \tForum deletion date and \tKnows deletion date.
\begin{itemize}
    \item $\varc{\eHasMember}_{\mathsf{w}} = \varc{\eKnows_{i,j}} + \Delta$
    \item $\vard{\eHasMember}_{\mathsf{w}} = \min(\vard{\eForum}_{\mathsf{w}}, \vard{\eKnows_{i,j}})$
\end{itemize}

\subsubsection{Albums}
A \tPerson can create multiple Albums ($\eForum_\textsf{a}$) containing a set of \tPhotos{}. Albums can be created and then deleted at any point during the lifespan of the \tPerson.
\begin{itemize}
    \item $\varc{\eForum}_\textsf{a} \in \interval{\varc{\ePerson} + \Delta}{\min (\vard{\ePerson}, \xSE)}$
    \item $\vard{\eForum}_\textsf{a} \in \interval{ \varc{\eForum}_\textsf{a} + \Delta}{\vard{\ePerson}}$
\end{itemize}

\paragraph{Album Moderator}
The \tPerson is the moderator for any Album they create. Album ownership cannot change hence \tHasModerator $\eHasModerator_{\mathsf{a}}$ gets the creation date (incremented by $\Delta$) and deletion date from $\varc{\eForum}_\textsf{a}$ and $\vard{\eForum}_\textsf{a}$ respectively.
\begin{itemize}
\item $\varc{\eHasModerator}_{\mathsf{a}} = \varc{\eForum}_{\mathsf{a}} + \Delta$
\item $\vard{\eHasModerator}_{\mathsf{a}} = \vard{\eForum}_{\mathsf{a}}$
\end{itemize}

\paragraph{Album Membership}
Only friends $\ePerson_i$ of a \tPerson $\ePerson_j$ can become members of Albums created by $\ePerson_j$. The \tHasMember $\eHasMember_{\mathsf{a}}$ edge creation date is derived from the Album and $\type{knows}$ creation dates. The deletion is derived from the $\type{Forum}$ and $\type{knows}$ deletion dates.
\begin{itemize}
    \item $\varc{\eHasMember}_\textsf{a} = \max ( \varc{\eForum}_\textsf{a}, \varc{\eKnows}_{i,j} ) + \Delta $
    \item $\vard{\eHasMember}_{\mathsf{w}} = \min ( \vard{\eForum}_\textsf{a}, \vard{\eKnows}_{i,j} ) $
\end{itemize}

\subsection{Message}
\label{sec:message}

A \tMessage is an abstract entity that represents a message created by a \tPerson.
There are two \tMessage subtypes: \tPost and \tComment.
A \tPost is created in a \tForum and a \tComment represents a comment made by a \tPerson to an existing \tMessage (either a \tPost or a \tComment).
In a \tForum the set of \tMessage nodes form a \emph{tree} with a \tPost node at the root and \tComment nodes for the rest.

\subsubsection{Post}

A \tPost can be created by a \tPerson in a \tForum.
Only the moderator (\ie owner) can post on a Wall or in an Album (\tHasModerator),
whereas all members including the moderator (\tHasMember/\tHasModerator) can post in a Group.
These relationships are captured with the $\eHasMember$ variable in the formulas.
\tPosts are divided in three categories, \emph{regular posts}, \emph{photos}, and \emph{flashmob posts}.

\paragraph{Regular Posts and Photos}

Regular posts capture the standard daily activity in a Group or on a Wall.
Photos are created in Albums. (Interaction with Photos is limited to \tLikes, see details in \autoref{sec:likes}). The creation date for these is determined as follows:
$$\varc{\ePost} \in \interval{\varc{\eHasMember} + \Delta}{\min (\vard{\eHasMember}, \xSE) }$$

\paragraph{Flashmob Posts}

Flashmob posts are generated around events that attract significant interest
(such as elections) that result in a spike in activity.
These events span a $2\phi$-hour time window centered around a specific event time, flashmob event $\eFlashmobEvent$, in the middle of the window; there are $\phi$ hours each side of the specific event time.
$$
\varc{\ePost} \in \interval{\max(\varc{\eHasMember} + \Delta,\eFlashmobEvent - \phi\textrm{\,h})}{\min (\vard{\eHasMember},\eFlashmobEvent + \phi\textrm{\,h},\xSE)}
$$

The deletion dates for all categories of \tPosts are determined as:
$$\vard{\ePost} \in \interval{\varc{\ePost} + \Delta}{\vard{\eHasMember}}$$

\paragraph{containerOf edge}

Each \tPost node has an incoming $\type{containerOf}$ edge which gets the same lifespan attributes as the \tPost.

\subsubsection{Comment}

A \tComment $\eComment$ is created by \tPerson $\ePerson$ as a reply to \tMessage $\eMessage$. \tComments are only made in Walls and Groups. \tComment always occur within $\gamma$~days of their parent message following a power-law distribution with mean 6.85 hours.

\begin{itemize}
    \item $\varc{\eComment} \in \interval{\max (\varc{\eMessage}, \varc{\eHasMember}) + \Delta}{\min (\vard{\eMessage}, \vard{\eHasMember}, \varc{\eMessage} + \gamma\textrm{\,d}, \xSE)}$
    \item $\vard{\eComment} \in \interval{\varc{\eComment} + \Delta}{\min (\vard{\eMessage}, \vard{\eHasMember})}$
\end{itemize}

\paragraph{replyOf edge}

\tComments always have an outgoing \tReplyOf edge with containment semantics, \ie the target \tMessage contains the \tComment. These edges get the same lifespan as their source \tComment.

\subsubsection{likes}
\label{sec:likes}

A \tLikes edge $\eLikes$ can exist between \tPerson $\ePerson$ and \tMessage $\eMessage$. Messages can only receive likes during a $\mu$-day window after their creation at which point no more activity is generated.

\begin{itemize}
    \item $\varc{\eLikes} \in \interval{\max(\varc{\ePerson}, \varc{\eMessage}) + \Delta}{\min (\vard{\ePerson}, \vard{\eMessage}, \varc{\eMessage} + \mu\textrm{\,d}, \xSE)}$
    \item $\vard{\eLikes} \in \interval{\varc{\eLikes} + \Delta}{\min (\vard{\ePerson}, \vard{\eMessage})}$
\end{itemize}


\IEEEPARstart{A}{udio} localization in stereophonic recording focuses on balancing the pressure level and time difference cues that inform audio localization through interaural time differences (ITD) and interaural level differences (ILD). Within the stereophonic recording praxis, it is understood that the weighting of ITD and ILD cues contributes to varying desirable qualities within the resultant soundfield. Stereophonic microphone arrays are also chosen to account for the desired balance of direct sound and reflected sound and to accommodate the recording angle of the perceptual "soundstage" and translate it to audio reproduction systems with minimal angular distortion.

This is, however, at odds with typical stereophonic localization practice within the application of audio signal processors; which tend to prioritize localization solely through ILD cues. In certain contexts this can lead to a situation where recorded signals that are being mixed together during post-production can be localized using different perceptual locative cues, yet with the intent of producing a coherent, and qualitatively consistent perceptual soundstage.

By modelling the time and level relationships between a sound source and the microphones in a stereophonic recording array, a monophonically recorded sound can be localized within the perceptual soundstage using the time and level cues appropriate to the modeled array. This paper will outline an algorithm and discuss and implementation for abstracting these relationships in to a CPU-efficient model, and exposing the appropriate parameters to the user.

\subsection{A Review of Localization in Stereo Recording}

Within the context of localization, it is understood that a relative dominance of time-domain cues creates a greater perceived sense of stereophonic width/envelopment, whereas a greater relative preponderance of level-based cues increases the sense of locative precision. Microphones, as pressure transducers, encode local changes in atmospheric pressure into changes in electrical pressure, and can be practically thought of as sampled points in space. Additionally, microphones have varying types of directivity -- represented by a polar plot -- that represent how efficiently they transduce sound based on the sound-wave angle of arrival relative to the microphone's orientation. For directional microphones with cardioid-style polar patterns, the amount of attenuation tends to increase as the sound-wave's direction of arrival moves further away from the oriented "front" of the microphone\footnote{There is some complexity with this as the directivity pattern value increases past a pure-cardioid, with an inverse-phase area beginning to present at the rear of the microphone and increasing until the directivity approaches a bidirectional pattern}.

By positioning two directional microphones in the same location and facing in two different directions, any sound-wave captured by them will be increasingly less attenuated as it approaches the front of one microphone and more attenuated as it approaches the other. If the sound wave approaches from an angle that equiangular to both microphones, then it will be equally attenuated. This equal attenuation, during reproduction, will have the perceptual effect of placing the sound at the center of the virtual sound-stage.

Similarly, by positioning two nondirectional microphones in to locations within the space, the distance between them will create differences in the time of arrival based on the speed of propagation of the sound-wave (the speed of sound). As the direction of arrival shifts away from being perpendicular to an imaginary line drawn from one microphone to the other, there will be an increasing time delay between when the sound is captured in the closer microphone and when it is captured in the further microphone. As with the level-based cues, when the time of arrival is equal (i.e. there is no delay in one microphone) then the perceptual effect during reproduction is one of the sound being centered in the perceptual soundstage. As the delay increases in one microphone, the sound will appear to come from the direction in which it arrives first\footnote{This phenomenon is known as the "precedence effect"}.

These level and time-based principles can be freely combined, creating a spectrum of options for recording engineers to choose from. More advanced methodologies will add in a center microphone (such as the popular "Decca-Tree" configuration), and/or will also add flanking/outrigger microphones as well. The combined effect of these various microphone set-ups yields a complex interplay of time and level cues.

\subsection{Signal-Processing Panning Methods}

Current methods in stereophonic panning within digital audio workstations (DAW) typically focus on the manipulation of level differences. These level differences tend to follow either a sine-cosine (see \ref{threedB}) or a linear curve (see \ref{sixdB}).

For $\{p \: | \: 0 \leq p \leq 1\}$ to represent the range of the user input value for stereophonic panning, then the normal panning functions can be found as:

\begin{equation} \label{threedB}
\begin{bmatrix}L \\ R \end{bmatrix} = x * \begin{bmatrix} \cos{\frac{p\pi}{2}} \\ \sin{\frac{p\pi}{2}} \end{bmatrix}
\end{equation}

\begin{equation}\label{sixdB}
\begin{bmatrix}L \\ R \end{bmatrix} = x * \begin{bmatrix} p \\ 1 - p \end{bmatrix}
\end{equation}

Interestingly, there is not as accepted standard functionality for DAWs to perform panning based on time-domain cues. Multiple reasons can be found for this, though the two that arguably stand out are: lack of monophonic compatibility due to phase distortions, and tradition from analogue mixing consoles which were unable to provide the delay lines necessary. Additionally, the usage of computer memory for the circular-buffer delay-lines needed may have also been a consideration against memory availability in early computers.

The use of time-domain cue is either implemented through a stereo "widener\footnote{The implementation of stereo widening techniques varies from processor to processor, not all will use the same methods. Any given widener may not actually use time-based cues, relying instead solely on frequency-domain adjustments or dynamics range processing.}" or by manual implementation through simple or purpose-built delay audio plug-ins in a technique known as the "Haas Trick\footnote{after Helmut Haas, who studied the psychoacoustical implications of the precedence effect in his Ph.D. thesis.}."

\subsection{Purpose}

This paper will describe an algorithm for modeling the interplay of the microphones within a stereophonic recording array; and discuss an audio plug-in that implements this algorithm. This algorithm and the accompanying audio processor were developed as an entry to the AES/MATLAB Plugin Competition in 2020. As such, the processor developed was designed to work within the limits of the competition -- most specifically the two-channel input/output requirement, and the goal to solve a specific use-case scenario. Theoretically, this algorithm could be applied to any arbitrary microphone set-up and source placement within a virtual space.

The immediate use-cases intended to be addressed with this specific implementation are: 1. the placement of monophonically recorded sources into a stereophonic microphone array, and 2. the addition of time-domain cues through a UI that is intuitive and effective, and yields natural and predictable results.

\subsubsection{Blending monophonic encoded sources}

When recording acoustic ensembles, recording engineers will frequently employ both a main stereo array and area/spot microphones. These spot microphones are used to accentuate various parts of the ensemble to difference logistical and aesthetic ends. Drawing from previous sections, stereo recording praxis and panning implementation in DAWs do not agree on how to encode stereophonic localization cues. This can quickly lead to a situation where the sound of an instrument recorded in an ensemble with both a stereo array and spot microphone will have a mixture of time/level cues in the main array signal, but only be localized with level cues in the panned signal from the spot microphone. Due to the differences in the perceptual effect of time and level cues, this can lead to inconsistencies in the quality of the soundfield as the dominance of the source of the instrument in the audio mix changes between the main array and the spot microphones; this may also cause inconsistency in instruments that are around the spot microphone. The use of this processor will encode the monophonic sound with time and level cues that closely match that of the main array, meaning that its localization and sense of envelopment will not change based on the dominance of the source.

Following this, another context for this application of the processor is in blending a monophonic recorded source into a recording that was taken of an ensemble using a stereophonic microphone array. "Distributed recording" is not uncommon -- especially in music for media. It is not uncommon for sections of an ensemble to be recorded independently and then put together during post-production. This processor would allow for independently recorded instruments to be better blended into a larger ensemble by encoding them with the same localization cues, creating a greater qualitative unity in the resultant soundfield.

This also has implications for sample-based music production and the common practice of laying samples of the same instrument family that come from different sample libraries. Commercial sample libraries each have their own recording and staging procedures, and different instruments and sections can be localized using different combinations of level and time-domain cues. The use of this processor on the spot microphone or monophonic summed options will allow for the sounds to be spatialized together in a more consistent manner.

Finally, this processor can also be used in conjunction with standard post-processing artificial reverberation techniques to manufacture a sense of unity from completely independently recorded instruments by encoding them onto a virtual soundstage using natural level and time-domain cues.

\subsubsection{Time-domain cues in panning}

A secondary use for this processor is in presenting an intuitive method of adding time-domain cues into panning. Rather than relying on an arbitrary implementation of the Haas trick, a user of this processor can -- through the familiar metaphor of a stereophonic microphone pair -- creating a consistent, repeatable, and intuitive panning plan for components of their audio mixdown that includes both time and level perceptual components.


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath,amssymb}
\usepackage{hyperref}

\newcommand{\func}[1]{\mathsf{#1}}

\title{Haven Protocol code notes}
\author{Cypher Stack\thanks{\url{https://cypherstack.com}}}
\date{\today}

\begin{document}

\maketitle

\section{Introduction}

This document describes technical information relevant to Haven Protocol.
It reflects a snapshot of the codebase repository\footnote{\url{https://github.com/haven-protocol-org/haven-main/tree/v2.0.0-rc3}}, but its findings and observations may be superseded by later changes.
As with any code review, this analysis is limited and cannot capture all use cases or unintended behaviors of the codebase in all circumstances; it reflects a best-effort approach of the author to determine the extent to which relevant portions of the codebase reflect verification operations in the transaction protocol description\footnote{\url{https://github.com/cypherstack/haven-protocol-review/releases/tag/final}} approved by its designers.
It does not specifically address the scope of best-practice secure C\texttt{++} design principles, for which the authors recommend further detailed review.
The author asserts no warranty and disclaims liability for its use.
The author further expresses no endorsement of Haven Protocol or its associated entities.

\section{Structure}

In this section, we describe the structural similarities and differences between the protocol description and its implementation.

\subsection{Transaction types}

The protocol description describes two types of transactions: \textit{transfer} and \textit{conversion}.
Transfer transactions consume and generate assets of a single type, where balance is asserted if the combined value of spent inputs is equal to the combined value of generated outputs.
Conversion transactions consume assets of a single type, and generate assets of the consumed type and a single additional type.
In this case, balance is asserted if the combined value of spent input inputs is equal to the combined value of generated outputs after applying a scaling factor produced by a pricing oracle.

The protocol description requires that transfer transactions generate at least two outputs, which mitigates analysis based on knowledge of commitment masks or values.
It requires that conversion transactions generate at least one output of each of the two required types, but discussions with the designers indicate the intent is to require at least two source- and destination-type generated outputs.

The implementation differs from the protocol in further delineating transaction types based on specific asset types.
Transaction types are defined in \texttt{cryptonote::transaction\_type}, and are inferred from given source and destination strings in \texttt{cryptonote::get\_tx\_type}:
\begin{itemize}
	\item \texttt{UNSET}: no type has been specified
	\item \texttt{TRANSFER}: source and destination types are both \texttt{XHV}
	\item \texttt{OFFSHORE\_TRANSFER}: source and destination types are both \texttt{XUSD}
	\item \texttt{XASSET\_TRANSFER}: source and destination types are the same, but neither \texttt{XHV} nor \texttt{XUSD}
	\item \texttt{OFFSHORE}: source type is \texttt{XHV} and destination type is \texttt{XUSD}
	\item \texttt{ONSHORE}: source type is \texttt{XUSD} and destination type is \texttt{XHV}
	\item \texttt{XUSD\_TO\_XASSET}: source type is \texttt{XUSD} and destination type is neither \texttt{XHV} nor \texttt{XUSD}
	\item \texttt{XASSET\_TO\_XUSD}: source type is neither \texttt{XHV} nor \texttt{XUSD}, and destination type is \texttt{XUSD}
\end{itemize}
Any other combination of source and destination strings is rejected.

\subsection{Asset types}

Source and destination asset type strings for a transaction are established in \texttt{cryptonote::get\_tx\_asset\_types}, where protocol consistency rules are applied based on the structure of consumed and generated transaction outputs:
\begin{enumerate}
	\item The transaction must consume only a single asset type, which is defined to be the source asset type.
	\item If the transaction is a miner transaction, the destination asset type is defined to be the base \texttt{HXV} asset type, and no source transaction type is specifically defined.
	\item If the transaction is not a miner transaction and generates a single asset type, it must match the source asset type and is defined to be the destination asset type.
	\item If the transaction is not a miner transaction and generates two asset types, exactly one of them must match the source asset type; both are defined to be the destination asset types.
	\item If the transaction is not a miner transaction, it may not generate outputs of more than two asset types.
	\item All source and destination asset types must belong to the static list defined in \texttt{offshore:ASSET\_TYPES}.
\end{enumerate}
These rules differ from the protocol description.
Miner transactions, which are part of the parent transaction protocol, are not specifically defined in the scoped transaction protocol, but are restricted in implementation to the base asset; notably, miner transaction output types are not checked in this function to be of the base asset type; the destination asset type is set manually.
Source and destination types default to an empty string, which is not specifically defined as either an asset type nor an indicated error condition.

\subsection{Transfer transaction balance}

The balance logic for transfer transactions of the types \texttt{OFFSHORE\_TRANSFER}, \texttt{TRANSFER}, and \texttt{XASSET\_TRANSFER} is established and checked in the function \texttt{rct::verRctSemanticsSimple2}.
This function assumes prior establishment of source and destination asset type strings, which are checked against the static list of valid types.
In the case of transfer transactions, the source and destination type are identical.
The function is intended to process transfer and conversion transactions, and so we must ensure that the common logic applies to the specific protocol requirements of transfer transactions.
Using the notation of the protocol description, the following is computed and checked:
$$\sum_{u=0}^{w-1} C_u' - \func{Com}(f,0) - \func{Com}(f',0) - \sum_{j=0}^{t-1} \overline{C}_j = 0$$
Here $f$ is the transaction fee and $f'$ is the \textit{offshore fee} as noted in code comments.
The offshore fee is not captured by the protocol description, but is handled in the same manner as the transaction fee.
Transactions of type \texttt{TRANSFER} have the logic applied as the result of a default condition of a conditional block that checks against possible types; if another transaction type were presented that was not of the types in this block, it would evaluate using the transfer logic.

\subsection{Conversion transaction balance}

The balance logic for conversion transactions of the types \texttt{OFFSHORE}, \texttt{ONSHORE}, \texttt{XUSD\_TO\_XASSET}, and \texttt{XASSET\_TO\_XUSD} is also established and checked in the same function.
In these cases, the source and destination asset type strings are different, but checked against the static list of valid types.
Using the notation of the protocol description, the following is computed and checked:
$$\sum_{u=0}^{w-1} C_u' - \func{Com}(f,0) - \func{Com}(f',0) - \sum_{j=0}^{n_T-1} \overline{C}_j - \frac{1}{r} \sum_{n_T}^{t-1} \overline{C}_j = 0$$
Here, the value of $r$ is scaled by an atomic unit factor $\texttt{COIN}$ depending on whether \texttt{XUSD} is a source or destination asset type.
As with transfer transactions, the offshore fee is not captured by the protocol description.
Further, atomic unit conversions to and from \texttt{XUSD} type are not captured by the protocol description.

\subsection{Burn amount verification}

The conversion burn amount verification check required by the protocol also takes place in \texttt{rct::verRctSemanticsSimple2}.
This is intended to confirm a plaintext amount sum for the source asset type corresponds validly to the associated commitments presented in the transaction.
According to the protocol description, this is asserted by the following check:
$$\sum_{u=0}^{w-1} C_u' - \sum_{j=0}^{n_T-1} \overline{C}_j - \func{Com}(f,0) - \func{Com}(0,a_T - \overline{a}_T) - \func{Com}(y_T,0) = 0$$
The check performed in the implementation differs in its commitment construction, performing this check:
$$\sum_{u=0}^{w-1} C_u' - \sum_{j=0}^{n_T-1} \overline{C}_j + \func{Com}(0,\overline{a}_T) = \func{Com}(y_T - f'',a_T) = 0$$
Here $f''$ is defined in the code as a scaled \textit{burn fee} computed from the offshore fee, which is not captured by the protocol description.
Note that while the commitments constructed in the implementation differ from the construction method in the protocol, they are algebraically equivalent (aside from the burn fee).

\subsection{Mint amount verification}

The conversion mint amount verification check required by the protocol takes place in the function \texttt{rct::checkBurntAndMinted}, which is called from the function \texttt{tx\_memory\_pool::add\_tx2}.
This is intended to check a claimed plaintext amount sum for the destination asset type.
As noted in the protocol description, this is not checked against commitments presented in the transaction.
It appears that a user generating such a transaction could simply provide a plaintext minted amount sum satisfying the check without any particular correspondence to commitments; however, we argue in the protocol description that security is not reduced by removing this check altogether.
The verifier can produce the value on its own if needed, and avoid relying on the value provided in the transaction.

\subsection{Linkable ring signature}

Both transfer and conversion transactions require a linkable ring signature on each consumed source asset.
The protocol description assumes the use of CLSAG signatures for this use.
The implementation uses the CLSAG implementation from its parent codebase, where verification of signatures is performed within \texttt{rct::verRctCLSAGSimple}, which binds an arbitrary message into the signature.
The implementation of \texttt{rct::verRctCLSAGSimple} appears to be correctly ported from the parent codebase.
While the protocol description does not specify the format of the message bound to each CLSAG signature, it should be checked that this message includes any replay-specific mitigations relevant to transactions that may differ from the parent codebase.

\subsection{Range proofs}

Generated outputs in both transfer and conversion transactions require one or more range proofs to assert committed values are within a protocol-specified range.
The protocol description assumes the use of the Bulletproofs range proving system for this use.
The implementation uses the Bulletproofs implementation from its parent codebase, where verification of aggregated proofs is performed within \texttt{rct::verBulletproof}.
The implementation of the verification wrapper \texttt{rct::verBulletproof} (and its underlying direct verification function) appears to be correct as unchanged from its parent repository.
Atomic unit conversion is not performed prior to range proof verification, as this is done for balance purposes separately.

\section{Observations}

In this section, we describe findings and observations within the Haven Protocol codebase relevant to verification in the transaction protocol, and note possible suggestions for improvement where appropriate.

\subsection{Pricing oracles}

The protocol relies heavily on a single pricing oracle that is assumed to securely provide responses to queries for asset conversion rates.
No checks are assumed to be made about the consistency of its responses.
The implementation relies on a set of hardcoded oracles \texttt{config::ORACLE\_URLS} defined for the live network and test networks; for each network, the oracles share a single verification public key.

Oracle queries are performed in \texttt{Blockchain::get\_pricing\_record}.
This function shuffles the oracle list (presumably for load balancing reasons), and then queries the shuffled list until a response is returned.
The query includes a network version flag and encoded block timestamp.
On receipt of a response, the function verifies a response signature against the hardcoded public key.
If verification fails or no response is received from any oracle, an empty response is constructed that instantiates with zero values.
The result is used to populate a pricing record on each supported asset type.

The oracle implementation currently deployed returns JSON data consisting of asset types with integer-valued conversion rates, a timestamp, an encoded signature, and unused auxiliary data.
To verify the signature, a JSON string is reconstructed with all asset types, corresponding conversion rates, and timestamp (if nonzero).
Signature values are decoded using a method that is not documented.
The algorithm used to verify the signature is not made explicit, as it appears to be inferred from the encoded public key.
Based on limited comments in the code, it may be ECDSA, but this is not confirmed.

All hardcoded mainnet oracles accept HTTPS queries on port 443, reject HTTP queries on port 80, and reject HTTP queries on port 443.
Oracles are hardcoded by domain and not IP, appear to defer to the user's chosen DNS provider for IP resolution, and appear to defer to the user's local certificate authority for server authentication.

\subsection{Pricing record inversion}

In balance computation, pricing record values are converted to scalar field elements and may be multiplicatively inverted.
The inversion algorithm is only guaranteed to succeed on nonzero input; there is a check within the \texttt{invert} function that will fail on zero input, but it only runs on the presence of a debugging flag.
The pricing record values in balance computation are not tested within \texttt{verRctSemanticsSimple2} to assert they are nonzero.
Pricing oracle queries may return zero values, or the entire query may fail and result in a zero-default pricing record instantiation.
There exists a check in \texttt{tx\_memory\_pool::add\_tx2} against zero-value specific entries within pricing records.
A safer additional guard is to enable the inversion check on production builds; the operation is extremely efficient, and is the most direct guarantee that the algorithm succeeded.
Another safe option is to test input scalars to the inversion function to assert they are nonero; this check would also be extremely efficient.

\subsection{Common key type}
\label{obs:common-key-type}

The codebase, like that of its upstream parent, uses a single byte array type \texttt{rct::key} to represent two underlying mathematical types: elliptic curve group elements and elements of this group's scalar field.
Both element types have canonical 32-byte representations, but they are not directly algebraically compatible.
A comprehensive codebase update might use separate byte array types for curve group and scalar elements in order to reduce confusion and the likelihood of errors in algorithm design or implementation; however, this common type is widely used throughout the implementation, implying risk in such a wide-ranging change that would need to be carefully considered.

\subsection{Inconsistent key initialization}
\label{obs:key-initialization}

Related to Observation \ref{obs:common-key-type}, group and scalar elements are occasionally initialized inconsistently.
The zero scalar is defined using the \texttt{rct::zero()} function, which returns a constant byte array \texttt{(0x00,...,0x00)} as its canonical byte representation.
The zero (identity) group element is defined using the \texttt{rct::identity()} function, which returns as its canonical byte representation a constant byte array \texttt{(0x01,0x00,...,0x00)}.
However, several locations in \texttt{rctSigs.cpp} initialize group elements unexpectedly using \texttt{rct::zero()} or \texttt{memwipe}, which could have unintended behavior if these values are not later set directly or by appropriate function calls to other algorithms or operations.

Examples of this behavior include:
\begin{itemize}
	\item \texttt{rctSigs.cpp}, lines 933-935
	\item \texttt{rctSigs.cpp}, line 1328
	\item \texttt{rctSigs.cpp}, line 1584
\end{itemize}
Relying on later function calls or algorithms to reset group elements to another value is not robust, and may lead to unsafe results.
Care should be taken to initialize group and scalar elements correctly when using \texttt{rct::key}, as it is not always obvious from context which element type is intended.

\subsection{Inconsistent asserts}
\label{obs:asserts}

Low-level balance verification in \texttt{verRctSemanticsSimple2} performs computations on input and output data based on transaction and asset types discussed previously.
For this reason, it is essential that these types are valid and consistent.
The asserts contained in the low-level balance verification check that source and destination asset types are valid by their inclusion in \texttt{offshore::ASSET\_TYPES}.
Later, the balance computation sorts outputs by asset type, and then uses the transaction type to complete the computation.
However, this does not account for the required consistency between output asset types, source and destination asset type strings, and transaction type provided as function arguments.
Rather, these consistency checks are offloaded.
For this reason, the inclusion of one consistency check for valid source and destination asset type strings appears inconsistent, as it is also performed prior to the function being called.
It may be useful to standardize the validity and consistency checks between transaction types and asset types to improve reliability and efficiency, and reduce the possibility of error.
In particular, if these validity checks are not intended to be used in other parts of the protocol, it may be safest to call them directly from \texttt{verRctSemanticsSimple2} (to ensure they are run whenever this verification takes place), or to document carefully the requirements and assumptions on the function arguments.

\subsection{Underspecified transaction type check}
\label{obs:transaction-type-check}

When performing the balance check in \texttt{verRctSemanticsSimple2}, the transaction type is crucially used to identify the scaling and outputs to be used in the calculation.
This is done by building the sum-to-zero element \texttt{Zi} in a way that is dependent on the transaction type.
Generic \texttt{TRANSFER} transactions are not specifically checked by the conditional in balance verification, instead being the result of a default condition.

While this does not pose a problem if possible valid transaction types are not added, it would be safest to reject transactions not meeting the expected type, as there may be unintended behavior resulting from attempting to complete the computation and balance validity check on an unexpected transaction type.

\subsection{Unnecessary identity computations}

As noted in Observation \ref{obs:key-initialization}, the elliptic curve group identity element can be obtained via a call to \texttt{rct::identity()}, which returns a constant byte array consisting of the canonical representation of this element.

In several locations in \texttt{rctSigs.cpp}, the identity group element is computed by computing the scalar-group multiplication \texttt{scalarmultH(d2h(0))}, which is unnecessary and less efficient.

Examples of this behavior include:
\begin{itemize}
	\item \texttt{rctSigs.cpp}, line 1327
	\item \texttt{rctSigs.cpp}, line 1583
	\item \texttt{rctSigs.cpp}, line 1866
	\item \texttt{rctSigs.cpp}, line 1869
	\item \texttt{rctSigs.cpp}, line 1870
	\item \texttt{rctSigs.cpp}, line 1871
\end{itemize}
All such function calls can safely be replaced with \texttt{rct::identity()} calls for clarity and speed.

\subsection{Fee ranges}

The protocol description requires that fees be checked to lie within a protocol-specified range.
Because fees are presented in the clear, they do not come equipped with range proofs.
However, fees are used in the verification function \texttt{verRctSemanticsSimple2} to produce commitments that may overflow the balance check if not asserted to be within the required range.
All fees, including those outside of the scope of the protocol description, should be carefully checked to ensure they cannot overflow the balance check.
One way to ensure this is by suitable truncation encoding that is properly re-encoded to a scalar value for commitment computation.

\subsection{Undocumented signature verification}

As noted previously, pricing oracle responses come equipped with a signature that is verified prior to acceptance using \texttt{pricing\_record::verifySignature}.
However, the details of this verification process are not clearly documented.

In particular, the signature algorithm intended to be used for the public key appears to be inferred from the key type, which is not specified in the code.
Second, a comment indicates that the decoded signature is reformatted to match an OpenSSL format, but the details of the formatting operation are unclear, so it is not possible to properly assess.
Finally, the verification algorithm is unspecified at the time of verification (related, presumably, to the key type as noted above).

Because price oracle response validity is crucial to the safe operation of the protocol, the methods used to verify oracle signatures should be clearly documented.

A separate option (if reliance on OpenSSL functionality is not desired) may be to use a Schnorr signature on the oracle response, which could take advantage of structures and functions already present in the codebase, including those for deseralizing keys and signatures.
However, this change could introduce additional implementation risk and complexity.

\end{document}


\section{Free Energy of Conformational Change Calculations}
\label{section:fenergy}

\NAMD\ incorporates methods for performing free energy of conformational change perturbation calculations.
The system is efficient if only a few coordinates, either of individual atoms or centers of mass of groups of atoms, are needed.
The following configuration parameters are used to enable free energy perturbation:

\begin{itemize}

\item
\NAMDCONFWDEF{freeEnergy}{is free energy perturbation active?}{{\tt on} or {\tt off}}{{\tt off}}
{Specifies whether or not free energy perturbation is active.  If it
is set to {\tt off}, then no free energy perturbation is performed.
If it is set to {\tt on}, then the free energy perturbation calculation specified in
{\tt freeEnergyConfig} parameters is executed.}

\item
\NAMDCONF{freeEnergyConfig}{free energy perturbation script}{file or \{script\}}
{Must contain either the name of a free energy perturbation script file or the script
itself between \{ and \} (may include multiple lines).
This parameter may occur multiple times and scripts will be executed
in order of appearance.
The format of the free energy perturbation script is described below.
}

\end{itemize}

The following sections describe the format of the free energy perturbation script.

% Free energy perturbation parameters
% Free energy perturbation parameters, included into usage description

\subsection{User-Supplied Conformational Restraints}

These restraints extend the scope of the available restraints beyond that
provided by the harmonic position restraints. Each restraint is imposed with
a potential energy term, whose form depends on the type of the
restraint.\medskip

{\bf Fixed Restraints}

{\em Position restraint (1 atom):} force constant $K_{f}$, and reference
position $\overrightarrow{r_{ref}}$

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left( \left|
\overrightarrow{r_{i}}-\overrightarrow{r_{ref}}\right| \right) ^{2}$

{\em Stretch restraint (2 atoms):} force constant $K_{f}$, and reference
distance $d_{ref}$

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left(
d_{i}-d_{ref}\right) ^{2}$

{\em Bend restraint (3 atoms):} force constant $K_{f}$, and reference angle $
\theta _{ref}$

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left( \theta
_{i}-\theta _{ref}\right) ^{2}$

{\em Torsion restraint (4 atoms):} energy barrier $E_{0}$, and reference
angle $\chi _{ref}$

$\qquad \qquad \qquad \qquad E=\left( E_{0}/2\right) \left\{ 1-\cos \left(
\chi _{i}-\chi _{ref}\right) \right\} $

{\bf Forcing restraints}

{\em Position restraint (1 atom):} force constant $K_{f}$, and two reference
positions $\overrightarrow{r_{0}}$ and $\overrightarrow{r_{1}}$

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left( \left|
\overrightarrow{r_{i}}-\overrightarrow{r_{ref}}\right| \right) ^{2}$

$\qquad \qquad \qquad \qquad \overrightarrow{r_{ref}}$ $=\lambda
\overrightarrow{r_{1}}+\left( 1-\lambda \right) $ $\overrightarrow{r_{0}}$

{\em Stretch restraint (2 atoms):} force constant $K_{f}$, and two reference
distances $d_{0}$ and $d_{1}$

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left(
d_{i}-d_{ref}\right) ^{2}$

$\qquad \qquad \qquad \qquad d_{ref}=d_{1}+\left( 1-\lambda \right) d_{0}$

{\em Bend restraint (3 atoms):} force constant $K_{f}$, and two reference
angles $\theta _{0}$ and $\theta _{1}$

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left( \theta
_{i}-\theta _{ref}\right) ^{2}$

$\qquad \qquad \qquad \qquad \theta _{ref}=\lambda \theta _{1}+\left(
1-\lambda \right) \theta _{0}$

{\em Torsion restraint (4 atoms):} energy barrier E$_{0}$, and two reference
angles $\chi _{0}$ and $\chi _{1}$

$\qquad \qquad \qquad \qquad E=\left( E_{0}/2\right) \left\{ 1-\cos \left(
\chi _{i}-\chi _{ref}\right) \right\} $

$\qquad \qquad \qquad \qquad \chi _{ref}=\lambda \chi _{1}+\left( 1-\lambda
\right) \chi _{0}$

The forcing restraints depend on the coupling parameter, $\lambda $,
specified in a conformational forcing calculation. For example, the
restraint distance, $d_{ref}$, depends on $\lambda $, and as $\lambda $
changes two atoms or centers-of-mass are forced closer together or further
apart. In this case $K_{f}$ = $K_{f,0}$, the value supplied at input.

Alternatively, the value of $K_{f}$ may depend upon the coupling parameter
$\lambda$ according to:

$K_{f}$ = $K_{f,0} \lambda$

{\bf Bounds}

\begin{tabular}{ll}
{\em Position bound (1 atom):} & Force constant $K_{f}$, reference position $
\overrightarrow{r_{ref}}$, \\
& and upper or lower reference distance, $d_{ref}$
\end{tabular}

\qquad Upper bound:

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left(
d_{i}-d_{ref}\right) ^{2}$ for $d_{i}>d_{ref}$, else $E=0$.

\qquad Lower bound:

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left(
d_{i}-d_{ref}\right) ^{2}$ for $d_{i}$ $<$ $d_{ref}$, else $E=0$.\smallskip

$\qquad \qquad \qquad \qquad d_{i}^{2}=\left( \left| \overrightarrow{r_{i}}-
\overrightarrow{r_{ref}}\right| \right) ^{2}\medskip \medskip $

\begin{tabular}{ll}
{\em Distance bound (2 atoms):} & Force constant $K_{f}$, \\
& and upper or lower reference distance, $d_{ref}$
\end{tabular}

\qquad Upper bound:

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left(
d_{ij}-d_{ref}\right) ^{2}$ for $d_{ij}>d_{ref}$, else $E=0$.

\qquad Lower bound:

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left(
d_{ij}-d_{ref}\right) ^{2}$ for $d_{ij}<d_{ref}$, else $E=0$.\medskip
\medskip

\begin{tabular}{ll}
{\em Angle bound (3 atoms):} & Force constant $K_{f}$, \\
& and upper or lower reference angle, $\theta _{ref}$
\end{tabular}

\qquad Upper bound:

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left( \theta -\theta
_{ref}\right) ^{2}$ for $\theta >\theta _{ref},$ else $E=0$.

\qquad Lower bound:

$\qquad \qquad \qquad \qquad E=\left( K_{f}/2\right) \left( \theta -\theta
_{ref}\right) ^{2}$ for $\theta <\theta _{ref},$ else $E=0.\medskip \medskip
\medskip $

\begin{tabular}{ll}
{\em Torsion bound (4 atoms):} & An upper and lower bound must be provided
together. \\
& Energy gap $E_{0}$, lower AND upper reference angles, $\chi _{1}$ and $
\chi _{2}$, \\
& and angle~interval, $\Delta \chi .$
\end{tabular}

\qquad \qquad
\begin{tabular}{llll}
$\chi _{1}$ & $<\chi $ & $<\chi _{2}$ : & $E=0$ \\
$\left( \chi _{1}-\Delta \chi \right) $ & $<\chi $ & $<\chi _{1}$ : & $
E=\left( G/2\right) \left\{ 1-\cos \left( \chi -\chi _{1}\right) \right\} $
\\
$\chi _{2}$ & $<\chi $ & $\left( \chi _{2}+\Delta \chi \right) $: & $
E=\left( G/2\right) \left\{ 1-\cos \left( \chi -\chi _{2}\right) \right\} $
\\
$\left( \chi _{2}+\Delta \chi \right) ~$ & $<\chi $ & $\left( \chi
_{1}-\Delta \chi +2\pi \right) $ : & $E=G$
\end{tabular}

$\qquad \qquad G=E_{0}/\left\{ 1-\cos \left( \Delta \chi \right) \right\}
\bigskip $

Bounds may be used in pairs, to set a lower and upper bound. Torsional
bounds always are defined in pairs.

\subsection{Free Energy Calculations}

{\bf Conformational forcing / Potential of mean force}

In conformational forcing calculations, structural parameters such as atomic
positions, inter-atomic distances, and dihedral angles are forced to change
by application of changing restraint potentials. For example, the distance
between two atoms can be restrained by a potential to a mean distance that
is varied during the calculation. The free energy change (or potential of
mean force, pmf) for the process can be estimated during the simulation.

The potential is made to depend on a coupling parameter, $\lambda $, whose
value changes during the simulation. In potential of mean force
calculations, the reference value of the restraint potential depends on $
\lambda $. Alternately, the force constant for the restraint potential may
change in proportion to the coupling parameter. Such a calculation gives the
value of a restraint free energy, i.e., the free energy change of the
syste\bigskip m due to imposition of the restraint potential.

{\bf Methods for computing the free energy}

With conformational forcing (or with molecular transformation calculations)
one obtains a free energy difference for a process that is forced on the
system by changing the potential energy function that determines the
dynamics of the system. One always makes the changing potential depend on a
coupling parameter, $\lambda $. By convention, $\lambda $ can have values
only in the range from $0$ to $1$, and a value of $\lambda =0$ corresponds
to one defined state and a value of $\lambda =1$ corresponds to the other
defined state. Intermediate values of $\lambda $ correspond to intermediate
states; in the case of conformational forcing calculations these
intermediate states are physically realizable, but in the case of molecular
transformation calculations they are not.

The value of $\lambda $ is changed during the simulation. In the first
method provided here, the change in $\lambda $ is stepwise, while in the
second method it is virtually continuous.\medskip

{\em Multi-configurational thermodynamic integration (MCTI).}

In MCTI one accumulates $\,\left\langle \partial U/\partial \lambda
\right\rangle $ at several values of $\lambda $, and from these averages
estimates the integral

\qquad \qquad \qquad \qquad $-\Delta A=\int \,\left\langle \partial U/
\partial \lambda \right\rangle d\lambda $

With this method, the precision of each $\left\langle \partial U/\partial
\lambda \right\rangle $ can be estimated from the fluctuations of the time
series of $\partial U/\partial \lambda $.\bigskip

{\em Slow growth.}

In slow growth, $\lambda $ is incremented by $\delta \lambda =\pm 1/N_{step}$
after each dynamics integration time-step, and the pmf is estimated as

\qquad \qquad \qquad \qquad $-\Delta A=\Sigma $ $\left( \partial U/\partial
\lambda \right) $ $\delta \lambda $

Typically, slow growth is done in cycles of: equilibration at $\lambda =0$,
change to $\lambda =1$, equilibration at $\lambda =1$, change to $\lambda =0$
. It is usual to estimate the precision of slow growth simulations from the
results of successive cycles.

\subsection{Options for Conformational Restraints}

{\bf User-supplied restraint and bounds specifications}

\qquad \qquad urestraint $\{$

\qquad \qquad \quad n * (restraint or bound specification)\qquad \qquad //
see below

\qquad \qquad $\}\medskip $

{\bf Restraint Specifications (not coupled to pmf calculations)}

\qquad \qquad
\begin{tabular}{llll}
posi & ATOM & kf = KF & ref = (X Y Z) \\
dist & 2 x ATOM & kf = KF & ref = D \\
angle & 3 x ATOM & kf = KF & ref = A \\
dihe & 4 x ATOM & barr = B & ref = A
\end{tabular}
\bigskip

{\bf Bound Specifications (not coupled to pmf calculations)}

\qquad \qquad
\begin{tabular}{llll}
posi bound & ATOM & kf = KF & [low = (X Y Z D) or hi = (X Y Z D)] \\
dist bound & 2 x ATOM & kf = KF & [low = D or hi = D] \\
angle bound & 3 x ATOM & kf = KF & [low = A or hi = A] \\
dihe bound & 4 x ATOM & gap = E & low = A0\quad hi = A1\quad delta = A2
\end{tabular}
\bigskip

{\bf Forcing Restraint Specifications (coupled to pmf calculations)}

\qquad \qquad
\begin{tabular}{llll}
posi pmf & ATOM & kf=KF & low = (X0 Y0 Z0)\quad hi = (X1 Y1 Z1) \\
dist pmf & 2 x ATOM & kf=KF & low = D0\quad hi = D1 \\
angle pmf & 3 x ATOM & kf=KF & low = A0\quad hi = A1 \\
dihe pmf & 4 x ATOM & barr=B & low = A0\quad hi = A1
\end{tabular}
\bigskip

{\bf Units}

\qquad \qquad
\begin{tabular}{|c|c|}
\hline
Input item & Units \\ \hline
E, B & kcal/mol \\
X, Y, Z, D & %TCIMACRO{\UNICODE{0xc5}{}}
\\
A & degrees \\
$K_{f}$ & kcal/(mol %TCIMACRO{\UNICODE{0xc5}{}}
$^{2}$) or kcal/(mol rad$^{2}$) \\ \hline
\end{tabular}

\subsection{Options for ATOM Specification}

The designation ATOM, above, stands for one of the following forms:\medskip

{\bf A single atom}

(segname, resnum, atomname)

{\em Example:} (insulin, 10, ca)\medskip

{\bf All atoms of a single residue}

(segname, resnum)

{\em Example:} (insulin, 10)\medskip

{\bf A list of atoms}

group $\{$ (segname, resnum, atomname), (segname, resnum, atomname), $\ldots
$ $\}$

{\em Example:} group $\{$ (insulin, 10, ca), (insulin, 10, cb), (insulin,
11, cg) $\}\medskip $

{\bf All atoms in a list of residues}

group $\{$ (segname, resnum), (segname, resnum), $\ldots $ $\}$

{\em Example:} group $\{$ (insulin, 10), (insulin, 12), (insulin, 14) $
\}\medskip $

{\bf All atoms in a range of residues}

group $\{$ (segname, resnum) to (segname, resnum) $\}$

{\em Example:} group $\{$ (insulin, 10) to (insulin, 12) $\}\medskip $

{\bf One or more atomnames in a list of residues}

\begin{tabular}{l}
group $\{$ atomname: (segname, resnum), (segname, resnum), $\ldots $ $\}$ \\
group $\{$ (atomname, atomname, $\ldots $ ): (segname, resnum), (segname,
resnum), $\ldots $ $\}$
\end{tabular}

\begin{tabular}{ll}
{\em Examples:} & group $\{$ ca: (insulin, 10), (insulin, 12), (insulin, 14)
$\}$ \\
& group $\{$ (ca, cb, cg): (insulin, 10), (insulin, 12), (insulin, 14) $\}$
\\
& group $\{$ (ca, cb): (insulin, 10), (insulin, 12) cg: (insulin, 11),
(insulin, 12) $\}\smallskip $
\end{tabular}
\medskip

{\em Note: }Within a group, atomname is in effect until a new atomname is
used, or the keyword all is used. atomname will not carry over from group to
group. This note applies to the paragraph below.\medskip

{\bf One or more atomnames in a range of residues}

\begin{tabular}{l}
group $\{$ atomname: (segname, resnum) to (segname, resnum) $\}$ \\
group $\{$ (atomname, atomname, $\ldots $ ): (segname, resnum) to (segname,
resnum) $\}$
\end{tabular}

\begin{tabular}{ll}
{\em Examples:} & group $\{$ ca: (insulin, 10) to (insulin, 14) $\}$ \\
& group $\{$ (ca, cb, cg): (insulin, 10) to (insulin, 12) $\}$ \\
& group $\{$ (ca, cb): (insulin, 10) to (insulin, 12) all: (insulin, 13) $\}$
\end{tabular}

\subsection{Options for Potential of Mean Force Calculation}

The pmf and mcti blocks, below, are used to simultaneously control all
forcing restraints specified in urestraint above. These blocks are performed
consecutively, in the order they appear in the config file. The pmf block is
used to either a) smoothly vary $\lambda $ from 0 $\rightarrow $1 or 1 $
\rightarrow $0, or b) set lambda. The mcti block is used to vary $\lambda $
from 0 $\rightarrow $1 or 1 $\rightarrow $0 in steps, so that $\lambda $ is
fixed while $dU/d\lambda $ is accumulated.\medskip

{\bf Lamba control for slow growth}

pmf $\{$

~~task = [up, down, stop, grow, fade, or nogrow]

~~time = T [fs, ps, or ns] (default = ps)

~~lambda = Y (value of $\lambda $; only needed for stop and nogrow)

~~lambdat = Z (value of $\lambda _{t}$; only needed for grow, fade, and
nogrow) (default = 0)

~~print = P [fs, ps, or ns] or noprint (default = ps)

$\}\medskip $

\begin{tabular}{ll}
up, down, stop: & $\lambda $ is applied to the reference values. \\
grow, fade, nogrow: & $\,\lambda $ is applied to $K_{f}$. A fixed value, $
\lambda _{t}$, is used to determine the ref. values. \\
up, grow: & $\lambda $ changes from 0 $\rightarrow $1. (no value of $
\,\lambda $ is required) \\
down, fade: & $\lambda $ changes from 1 $\rightarrow $0. (no value of $
\,\lambda $ is required) \\
stop, nogrow: & dU/d$\lambda $ is accumulated (for single point
MCTI)\medskip \smallskip
\end{tabular}
\bigskip

{\bf Lambda control for automated MCTI}

mcti $\{$

~~task = [stepup, stepdown, stepgrow, or stepfade]

~~equiltime = T1 [fs, ps, or ns] (default = ps)

~~accumtime = T2 [fs, ps, or ns] (default = ps)

~~numsteps = N

~~lambdat = Z (value of $\lambda _{t}$; only needed for stepgrow, and
stepfade) (default = 0)

~~print = P [fs, ps, or ns] or noprint (default = ps)

$\}\medskip $

\begin{tabular}{ll}
stepup, stepdown: & $\lambda $ is applied to the reference values. \\
stepgrow, stepfade: & $\lambda $ is applied to $K_{f}$. A fixed value, $
\lambda _{t}$, is used to determine the ref. values. \\
stepup, stepgrow: & $\lambda $ changes from 0 $\rightarrow $1. (no value of $
\lambda $ is required) \\
stepdown, stepfade: & $\lambda $ changes from 1 $\rightarrow $0. (no value
of $\lambda $ is required)\medskip
\end{tabular}

For each task, $\lambda $ changes in steps of (1.0/N) from 0 $\rightarrow $1
or 1 $\rightarrow $0. At each step, no data is accumulated for the initial
period T1, then dU/d$\lambda $ is accumulated for T2. Therefore, the total
duration of an mcti block is (T1+T2) x N.

\subsection{Examples}

{\bf Fixed restraints}

\begin{tabular}{l}
{\footnotesize // 1. restrain the position of the ca atom of residue 0.} \\
{\footnotesize // 2. restrain the distance between the ca's of residues 0
and 10 to 5.2\AA } \\
{\footnotesize // 3. restrain the angle between the ca's of residues 0-10-20
to 90}$^{o}${\footnotesize \ .} \\
{\footnotesize // 4. restrain the dihedral angle between the ca's of
residues 0-10-20-30 to 180}$^{o}${\footnotesize \ .} \\
{\footnotesize // 5. restrain the angle between the centers-of-mass of
residues 0-10-20 to 90}$^{o}${\footnotesize \ .}
\end{tabular}

urestraint $\{$

~~posi (insulin, 0, ca) kf=20 ref=(10, 11, 11)

~~dist (insulin, 0, ca) (insulin, 10, ca) kf=20 ref=5.2

~~angle (insulin, 0, ca) (insulin, 10, ca) (insulin, 20, ca) kf=20 ref=90

~~dihe (insulin, 0, ca) (insulin, 10, ca) (insulin, 20, ca) (insulin, 30,
ca) barr=20 ref=180

~~angle (insulin, 0) (insulin, 10) (insulin, 20) kf=20 ref=90

$\}\bigskip $

\begin{tabular}{ll}
{\footnotesize // 1. } & {\footnotesize restrain the center of mass of three
atoms of residue 0.} \\
{\footnotesize // 2.} & {\footnotesize restrain the distance between (the
COM of 3 atoms of residue 0) to  (the COM of 3 atoms of residue 10).} \\
{\footnotesize // 3.} & {\footnotesize \ restrain the dihedral angle of
(10,11,12)-(15,16,17,18)-(20,22)-(30,31,32,34,35) to 90}$^{o}$ \\
{\footnotesize //} & {\footnotesize ( (ca of 10 to 12), (ca, cb, cg of 15 to
18), (all atoms of 20 and 22), (ca of 30, 31, 32, 34, all atoms of 35) ).}
\end{tabular}

urestraint $\{$

~~posi group $\{$(insulin, 0, ca), (insulin, 0, cb), (insulin, 0, cg)$\}$
kf=20 ref=(10, 11, 11)

~~
\begin{tabular}{ll}
dist & group $\{$(insulin, 0, ca), (insulin, 0, cb), (insulin, 0, cg)$\}$ \\
& group $\{$(insulin, 10, ca), (insulin, 10, cb), (insulin, 10, cg)$\}$
kf=20 ref=6.2
\end{tabular}

~~
\begin{tabular}{ll}
dihe & group $\{$ca: (insulin, 10) to (insulin, 12)$\}$ \\
& group $\{$(ca, cb, cg): (insulin, 15) to (insulin, 18)$\}$ \\
& group $\{$(insulin, 20), (insulin, 22)$\}$ \\
& group $\{$ca: (insulin, 30) to (insulin, 32), (insulin, 34), all:
(insulin, 35)$\}$ barr=20 ref=90
\end{tabular}

$\}$

{\bf Bound specifications}

\begin{tabular}{ll}
{\footnotesize // 1. } & {\footnotesize impose an upper bound if an atom's
position strays too far from a reference position.} \\
{\footnotesize // } & {\footnotesize (add an energy term if the atom is more
than 10\AA\ {}from (2.0, 2.0, 2.0) ).} \\
{\footnotesize // 2\&3.} & {\footnotesize \ impose lower and upper bounds on
the distance between the ca's of residues 5 and 15.} \\
{\footnotesize //} & {\footnotesize (if the separation is less than 5.0\AA\
{}or greater than 12.0\AA\ {}add an energy term).} \\
{\footnotesize // 4.} & {\footnotesize \ impose a lower bound on the angle
between the centers-of-mass of residues 3-6-9.} \\
{\footnotesize //} & {\footnotesize (if the angle goes lower than 90}$^{o}$
{\footnotesize \ apply a restraining potential).}
\end{tabular}

urestraint $\{$

~~posi bound (insulin, 3, cb) kf=20 hi = (2.0, 2.0, 2.0, 10.0)

~~dist bound (insulin, 5, ca) (insulin, 15, ca) kf=20 low = 5.0

~~dist bound (insulin, 5, ca) (insulin, 15, ca) kf=20 hi = 12.0

~~angle bound (insulin, 3) (insulin, 6) (insulin, 9) kf=20 low=90.0

$\}\bigskip $

\begin{tabular}{l}
{\footnotesize // torsional bounds are defined as pairs. this example
specifies upper and lower bounds on the} \\
{\footnotesize // dihedral angle, }$\chi ${\footnotesize {}, separating the
planes of the 1-2-3 residues and the 2-3-4 residues.}
\end{tabular}

%\begin{Body Text}
\begin{tabular}{llll}
{\footnotesize // The energy is 0 for:} & {\footnotesize -90}$^{o}$ &
{\footnotesize < }$\chi $ & {\footnotesize <\ 120}$
^{o}$ \\
{\footnotesize // The energy is 20 kcal/mol for:} & {\footnotesize 130}$^{o}$
& {\footnotesize <\ }$\chi $ & {\footnotesize <\
260}$^{o}$
\end{tabular}

\begin{tabular}{l}
{\footnotesize // Energy rises from 0 }$\rightarrow ${\footnotesize \ 20
kcal/mol as }$\chi ${\footnotesize \ {}increases from 120}$^{o}\rightarrow $
{\footnotesize \ 130}$^{o}${\footnotesize \ , and decreases from --90}$
^{o}\rightarrow ${\footnotesize \ --100}$^{o}${\footnotesize .}
\end{tabular}
%\end{Body Text}

urestraint $\{$

~~dihe bound (insulin 1) (insulin 2) (insulin 3) (insulin 4) gap=20 low=-90
hi=120 delta=10

$\}$

{\bf Forcing restraints}

\begin{tabular}{l}
{\footnotesize // a forcing restraint will be imposed on the distance
between the centers-of-mass of residues (10 to 15) and} \\
{\footnotesize // residues (30 to 35). low=20.0, hi=10.0, indicates that the
reference distance is 20.0%TCIMACRO{\UNICODE{0xc5}{}}
at }$\lambda ${\footnotesize =0, and 10.0%TCIMACRO{\UNICODE{0xc5}{}}
at }$\lambda ${\footnotesize =1.}
\end{tabular}

urestraint $\{$

~~
\begin{tabular}{ll}
dist pmf & group $\{$ (insulin, 10) to (insulin, 15) $\}$ \\
& \hspace{0pt}group $\{$ (insulin, 30) to (insulin, 35) $\}$ kf=20,
low=20.0, hi=10.0
\end{tabular}

$\}\medskip $

\begin{tabular}{l}
{\footnotesize // 1. during the initial 10 ps, increase the strength of the
forcing restraint to full strength: 0 }$\rightarrow $ {\footnotesize 20
kcal/(mol %TCIMACRO{\UNICODE{0xc5}{}}
}$^{2}${\footnotesize )} \\
{\footnotesize // 2. next, apply a force to slowly close the distance from
20 %TCIMACRO{\UNICODE{0xc5}{}}
to 10 %TCIMACRO{\UNICODE{0xc5}{}}
(}$\lambda ${\footnotesize \ changes from 0 }$\rightarrow ${\footnotesize \
1)} \\
{\footnotesize // 3. accumulate dU/d}$\lambda ${\footnotesize \ for another
10 ps. ( stays fixed at 1)} \\
{\footnotesize // 4. force the distance back to its initial value of 20
%TCIMACRO{\UNICODE{0xc5}{}}
( changes from 1 }$\rightarrow $ {\footnotesize 0)}
\end{tabular}

pmf $\{$

~~task = grow

~~time = 10 ps

~~print = 1 ps

$\}$

pmf $\{$

~~task = up

~~time = 100 ps

$\}$

pmf $\{$

~~task = stop

~~time = 10 ps

$\}$

pmf $\{$

~~task = down

~~time = 100 ps

$\}\medskip $

\begin{tabular}{ll}
{\footnotesize // 1. } & {\footnotesize force the distance to close from 20
%TCIMACRO{\UNICODE{0xc5}{}}
to 10 %TCIMACRO{\UNICODE{0xc5}{}}
in 5 steps. (}$\lambda ${\footnotesize \ changes from 0 }$\rightarrow $
{\footnotesize \ 1: ~~0.2, 0.4, 0.6, 0.8, 1.0)} \\
{\footnotesize // } & {\footnotesize at each step equilibrate for 10 ps,
then collect dU/d}$\lambda ${\footnotesize \ for another 10 ps.} \\
{\footnotesize //} & {\footnotesize ref = 18, 16, 14, 12, 10
%TCIMACRO{\UNICODE{0xc5}{}}
, duration = (10 + 10) x 5 = 100 ps.} \\
{\footnotesize // 2.} & {\footnotesize \ reverse the step above (}$\lambda $
{\footnotesize \ changes from 1 }$\rightarrow $ {\footnotesize 0: ~~0.8,
0.6, 0.4, 0.2, 0.0)}
\end{tabular}

mcti $\{$

~~task = stepup

~~equiltime = 10 ps

~~accumtime = 10 ps

~~numsteps = 5

~~print = 1 ps

$\}$

mcti $\{$

~~task = stepdown

$\}$

\subsection{Appendix}

{\bf Gradient for position restraint}

$E=\left( K_{f}/2\right) \left( \left| \overrightarrow{r_{i}}-
\overrightarrow{r_{ref}}\right| \right) ^{2}$

$E=\left( K_{f}/2\right) \left\{ \left( x_{i}-x_{ref}\right) ^{2}+\left(
y_{i}-y_{ref}\right) ^{2}+\left( z_{i}-z_{ref}\right) ^{2}\right\} $

$\nabla (E)=K_{f}\left\{ \left( x_{i}-x_{ref}\right) \overrightarrow{i}
+\left( y_{i}-y_{ref}\right) \overrightarrow{j}+\left( z_{i}-z_{ref}\right)
\overrightarrow{k}\right\} $

{\bf Gradient for stretch restraint}

$E=\left( K_{f}/2\right) \left( d_{i}-d_{ref}\right) ^{2}$

$d_{i}=\left\{ \left( x_{2}-x_{1}\right) ^{2}+\left( y_{2}-y_{1}\right)
^{2}+\left( z_{2}-z_{1}\right) ^{2}\right\} ^{1/2}$

$\nabla (E)=K_{f}\left( d_{i}-d_{ref}\right) \cdot \nabla (di)\medskip $

{\em for atom 2 moving, and atom 1 fixed}

$\nabla (d_{i})=1/2\left\{ \left( x_{2}-x_{1}\right) ^{2}+\left(
y_{2}-y_{1}\right) ^{2}+\left( z_{2}-z_{1}\right) ^{2}\right\}
^{-1/2}\left\{ 2\left( x_{2}-x_{1}\right) +2\left( y_{2}-y_{1}\right)
+2\left( z_{2}-z_{1}\right) \right\} $

$\nabla (d_{i})=\left\{ \left( x_{2}-x_{1}\right) \overrightarrow{i}+\left(
y_{2}-y_{1}\right) \overrightarrow{j}+\left( z_{2}-z_{1}\right)
\overrightarrow{k}\right\} /d_{i}$

$\nabla (E)=K_{f}\left\{ \left( d_{i}-d_{ref}\right) /d_{i}\right\} \left\{
\left( x_{2}-x_{1}\right) \overrightarrow{i}+\left( y_{2}-y_{1}\right)
\overrightarrow{j}+\left( z_{2}-z_{1}\right) \overrightarrow{k}\right\} $

{\bf Gradient for bend restraint}

$E=\left( K_{f}/2\right) \left( \theta _{i}-\theta _{ref}\right) ^{2}$

Atoms at positions A-B-C

distances: (A to B) = c; (A to C) = b; (B to C) = a;

$\theta _{i}=\cos ^{-1}(u)=\cos ^{-1}\left\{ \left( a^{2}+c^{2}-b^{2}\right)
/\left( 2ac\right) \right\} $

$\nabla (E)=K_{f}\left( \theta _{i}-\theta _{ref}\right) \cdot \nabla
(\theta _{i})$

$\nabla (\theta _{i})=\frac{-1}{\sqrt{1-u^{2}}}\cdot \nabla (u)\medskip $

{\em for atom A moving, atoms B \& C fixed (distances b and c
change)}

$\nabla (u)=\left\{ -b/\left( ac\right) \right\} \cdot \nabla (b)+\left\{
-a/\left( 2c^{2}\right) +1/\left( 2a\right) +b^{2}/\left( 2ac^{2}\right)
\right\} \cdot \nabla (c)$

$\nabla (b)=\left\{ \left( x_{A}-x_{C}\right) \overrightarrow{i}+\left(
y_{A}-y_{C}\right) \overrightarrow{j}+\left( z_{A}-z_{C}\right)
\overrightarrow{k}\right\} /b$

$\nabla (c)=\left\{ \left( x_{A}-x_{B}\right) \overrightarrow{i}+\left(
y_{A}-y_{B}\right) \overrightarrow{j}+\left( z_{A}-z_{B}\right)
\overrightarrow{k}\right\} /c\medskip $

{\em for atom B moving, atoms A \& C fixed (distances a and c
change)}

$\nabla (u)=\left\{ 1/(2c)+-c/(2a^{2})+b^{2}/(2a^{2}c)\right\} \cdot \nabla
(a)+\left\{ -a/\left( 2c^{2}\right) +1/(2a)+b^{2}/\left( 2ac^{2}\right)
\right\} \cdot \nabla (c)$

$\nabla (a)=\left\{ (x_{B}-x_{C})\overrightarrow{i}+(y_{B}-y_{C})
\overrightarrow{j}+(z_{B}-z_{C})\overrightarrow{k}\right\} /a$

$\nabla (c)=\left\{ (x_{B}-x_{A})\overrightarrow{i}+(y_{B}-y_{A})
\overrightarrow{j}+(z_{B}-z_{A})\overrightarrow{k}\right\} /c\medskip $

{\em for atom C moving, atoms A \& B fixed (distances a and b
change)}

$\nabla (u)=\left\{ -b/\left( ac\right) \right\} \cdot \nabla (b)+\left\{
-c/\left( 2a^{2}\right) +1/(2c)+b^{2}/\left( 2ac^{2}\right) \right\} \cdot
\nabla (a)$

$\nabla (b)=\left\{ (x_{C}-x_{A})\overrightarrow{i}+(y_{C}-y_{A})
\overrightarrow{j}+(z_{C}-z_{A})\overrightarrow{k}\right\} /b$

$\nabla (a)=\left\{ (x_{C}-x_{B})\overrightarrow{i}+(y_{C}-y_{B})
\overrightarrow{j}+(z_{C}-z_{B})\overrightarrow{k}\right\} /a $

{\bf Gradient for dihedral angle restraint}

$E=(E_{0}/2)\left\{ 1-\cos \left( \chi _{i}-\chi _{ref}\right) \right\} $

Atoms at positions A-B-C-D

$\chi _{i}=\cos ^{-1}(u)=$ $\cos ^{-1}\left( \frac{\overrightarrow{(CD}
\times \overrightarrow{CB})\bullet (\overrightarrow{BC}\times
\overrightarrow{BA})}{\left| \overrightarrow{CD}\times \overrightarrow{CB}
\right| \left| \overrightarrow{BC}\times \overrightarrow{BA}\right| }\right)
\qquad $AND

$\chi _{i}=\sin ^{-1}(v)=$ $\sin ^{-1}\left( \frac{\overrightarrow{(CD}
\times \overrightarrow{CB})\times (\overrightarrow{BC}\times \overrightarrow{
BA})}{\left| \overrightarrow{CD}\times \overrightarrow{CB}\right| \left|
\overrightarrow{BC}\times \overrightarrow{BA}\right| }\bullet \frac{
\overrightarrow{CB}}{\left| \overrightarrow{CB}\right| }\right) $

$\nabla (E)=(E_{0}/2)\left\{ \sin \left( \chi _{i}-\chi _{ref}\right)
\right\} \cdot \nabla (\chi _{i})$

$\nabla (\chi _{i})=\frac{-1}{\sqrt{1-u^{2}}}\cdot \nabla (u)\smallskip
\medskip $

\begin{tabular}{ll}
$\overrightarrow{CD}\times \overrightarrow{CB}$ $=$ & $
((y_{D}-y_{C})(z_{B}-z_{C})-(z_{D}-z_{C})(y_{B}-y_{C}))\overrightarrow{i}+$
\\
& $((z_{D}-z_{C})(x_{B}-x_{C})-(x_{D}-x_{C})(z_{B}-z_{C}))\overrightarrow{j}+
$ \\
& $((x_{D}-x_{C})(y_{B}-y_{C})-(y_{D}-y_{C})(x_{B}-x_{C}))\overrightarrow{k}$
\\
\multicolumn{1}{c}{$=$} & $p_{1}\overrightarrow{i}+p_{2}\overrightarrow{j}
+p_{3}\overrightarrow{k}$
\end{tabular}
\medskip \medskip

\begin{tabular}{ll}
$\overrightarrow{BC}\times \overrightarrow{BA}=$ & $
((y_{C}-y_{B})(z_{A}-z_{B})-(z_{C}-z_{B})(y_{A}-y_{B}))\overrightarrow{i}+$
\\
& $((z_{C}-z_{B})(x_{A}-x_{B})-(x_{C}-x_{B})(z_{A}-z_{B}))\overrightarrow{j}+
$ \\
& $((x_{C}-x_{B})(y_{A}-y_{B})-(y_{C}-y_{B})(x_{A}-x_{B}))\overrightarrow{k}$
\\
\multicolumn{1}{c}{$=$} & $p_{4}\overrightarrow{i}+p_{5}\overrightarrow{j}
+p_{6}\overrightarrow{k}$
\end{tabular}
\medskip \medskip

$u=\frac{p_{1}p_{4}+p_{2}p_{5}+p_{3}p_{6}}{\sqrt{
p_{1}^{2}+p_{2}^{2}+p_{3}^{2}}\sqrt{p_{4}^{2}+p_{5}^{2}+p_{6}^{2}}}\medskip
\medskip $

\begin{tabular}{ll}
$\nabla (u)=$ & $\frac{p_{1}\cdot \nabla (p_{4})+p_{2}\cdot \nabla
(p_{5})+p_{3}\cdot \nabla (p_{6})}{\sqrt{p_{1}^{2}+p_{2}^{2}+p_{3}^{2}}\sqrt{
p_{4}^{2}+p_{5}^{2}+p_{6}^{2}}}$ $+$ \\
& $\frac{p_{1}p_{4}+p_{2}p_{5}+p_{3}p_{6}}{\sqrt{
p_{1}^{2}+p_{2}^{2}+p_{3}^{2}}}$ $\left( -1/2\left(
p_{4}^{2}+p_{5}^{2}+p_{6}^{2}\right) ^{-3/2}\left( 2p_{4}\cdot \nabla
(p_{4})+2p_{5}\cdot \nabla (p_{5})+2p_{6}\cdot \nabla (p_{6})\right) \right)
$ $+$ \\
& $\frac{p_{1}p_{4}+p_{2}p_{5}+p_{3}p_{6}}{\sqrt{
p_{4}^{2}+p_{5}^{2}+p_{6}^{2}}}$ $\left( -1/2\left(
p_{1}^{2}+p_{2}^{2}+p_{3}^{2}\right) ^{-3/2}\left( 2p_{1}\cdot \nabla
(p_{1})+2p_{2}\cdot \nabla (p_{2})+2p_{3}\cdot \nabla (p_{3})\right) \right)
$
\end{tabular}

{\em for atom A moving, atoms B, C, \& D fixed}

\begin{tabular}{lrrr}
$\nabla (p_{1})=$ & $(0.0)\overrightarrow{i}+$ & $(0.0)\overrightarrow{j}+$
& $(0.0)\overrightarrow{k}$ \\
$\nabla (p_{2})=$ & $(0.0)\overrightarrow{i}+$ & $(0.0)\overrightarrow{j}+$
& $(0.0)\overrightarrow{k}$ \\
$\nabla (p_{3})=$ & $(0.0)\overrightarrow{i}+$ & $(0.0)\overrightarrow{j}+$
& $(0.0)\overrightarrow{k}$ \\
$\nabla (p_{4})=$ & $(0.0)\overrightarrow{i}+$ & $(z_{B}-z_{C})
\overrightarrow{j}+$ & $(y_{C}-y_{B})\overrightarrow{k}$ \\
$\nabla (p_{5})=$ & $(z_{C}-z_{B})\overrightarrow{i}+$ & $(0.0)
\overrightarrow{j}+$ & $(x_{B}-x_{C})\overrightarrow{k}$ \\
$\nabla (p_{6})=$ & $(y_{B}-y_{C})\overrightarrow{i}+$ & $(x_{C}-x_{B})
\overrightarrow{j}+$ & $(0.0)\nolinebreak \bigskip \overrightarrow{k}$
\end{tabular}
\bigskip

{\em for atom B moving, atoms A, C, \& D fixed}

\begin{tabular}{lrrr}
$\nabla (p_{1})=$ & $(0.0)\overrightarrow{i}+$ & $(z_{C}-z_{D})
\overrightarrow{j}+$ & $(y_{D}-y_{C})\overrightarrow{k}$ \\
$\nabla (p_{2})=$ & $(z_{D}-z_{C})\overrightarrow{i}+$ & $(0.0)
\overrightarrow{j}+$ & $(x_{C}-x_{D})\overrightarrow{k}$ \\
$\nabla (p_{3})=$ & $(y_{C}-y_{D})\overrightarrow{i}+$ & $(x_{D}-x_{C})
\overrightarrow{j}+$ & $(0.0)\overrightarrow{k}$ \\
$\nabla (p_{4})=$ & $(0.0)\overrightarrow{i}+$ & $(z_{C}-z_{A})
\overrightarrow{j}+$ & $(y_{A}-y_{C})\overrightarrow{k}$ \\
$\nabla (p_{5})=$ & $(z_{A}-z_{C})\overrightarrow{i}+$ & $(0.0)
\overrightarrow{j}+$ & $(x_{C}-x_{A})\overrightarrow{k}$ \\
$\nabla (p_{6})=$ & $(y_{C}-y_{A})\overrightarrow{i}+$ & $(x_{A}-x_{C})
\overrightarrow{j}+$ & $(0.0)\overrightarrow{k}$
\end{tabular}

{\bf Gradient for forcing position restraint}

$E=(K_{f}/2)\left( \left| \overrightarrow{r_{i}}-\overrightarrow{r_{ref}}
\right| \right) ^{2}$

$r_{ref}=\lambda \overrightarrow{r_{1}}+\left( 1-\lambda \right)
\overrightarrow{r_{0}}$

\begin{tabular}{lll}
$dE/d\lambda =$ & $K_{f}\times $ & $\left( \left( x_{i}-x_{ref}\right)
^{2}+\left( y_{i}-y_{ref}\right) ^{2}+\left( z_{i}-z_{ref}\right)
^{2}\right) ^{1/2}\times $ \\
&  & $1/2\left( \left( x_{i}-x_{ref}\right) ^{2}+\left( y_{i}-y_{ref}\right)
^{2}+\left( z_{i}-z_{ref}\right) ^{2}\right) ^{-1/2}\times $ \\
&  & $\left( 2\left( x_{i}-x_{ref}\right) \left( x_{0}-x_{1}\right) +2\left(
y_{i}-y_{ref}\right) \left( y_{0}-y_{1}\right) +2\left( z_{i}-z_{ref}\right)
\left( z_{0}-z_{1}\right) \right) $
\end{tabular}

$dE/d\lambda =K_{f}\times \left( \left( x_{i}-x_{ref}\right) \left(
x_{0}-x_{1}\right) +\left( y_{i}-y_{ref}\right) \left( y_{0}-y_{1}\right)
+\left( z_{i}-z_{ref}\right) \left( z_{0}-z_{1}\right) \right) \bigskip $

{\bf Gradient for forcing stretch restraint}

$E=\left( K_{f}/2\right) \left( d_{i}-d_{ref}\right) ^{2}$

$d_{ref}=\lambda d_{1}+\left( 1-\lambda \right) d_{0}$

$dE/d\lambda =K_{f}~\times ~\left( d_{i}-d_{ref}\right) ~\times ~\left(
d_{0}-d_{1}\right) \bigskip $

{\bf Gradient for forcing bend restraint}

$E=\left( K_{f}/2\right) \left( \theta _{i}-\theta _{ref}\right) ^{2}$

$\theta _{ref}=\lambda \theta _{1}+\left( 1-\lambda \right) \theta _{0}$

$dE/d\lambda =K_{f}~\times ~\left( \theta _{i}-\theta _{ref}\right) ~\times
~\left( \theta _{0}-\theta _{1}\right) \bigskip $

{\bf Gradient for forcing dihedral restraint}

$E=\left( E_{0}/2\right) \left( 1-\cos \left( \chi _{i}-\chi _{ref}\right)
\right) $

$\chi _{ref}=\lambda \chi _{1}+\left( 1-\lambda \right) \chi _{0}$

$dE/d\lambda =\left( E_{0}/2\right) ~\times ~\sin \left( \chi _{i}-\chi
_{ref}\right) ~\times ~\left( \chi _{0}-\chi _{1}\right) $


\section{Introduction}
\label{sec1}

When generating executable code from models by applying (sequences of) model transformations, the properties modeled initially in the source model have to be propagated to the target implementation.
In general, the target implementation is more complex, due to added implementation details, which makes its analysis more difficult, more time consuming, and in some cases even impossible, as described in Chapter~\ref{chap:exploring-boundaries}.
The source model, however, is relatively small, so its properties can be inspected and validated.
To check preservation of properties, one can analyze all or some of the intermediate models, but this means that a large portion of the analysis has to be duplicated.
In addition, this procedure has to be repeated for every new model, even if only small changes to the model have been made.

The efficient and general solution to this problem is to prove property preservation per transformation and to localize the proof only on the changes induced by the transformation.
In this chapter, we address research question \RQ{4} by presenting an approach that provides such a solution.

\RQFour

Our approach is demonstrated on \SLCO, the small but non-trivial domain-specific modeling language (DSML) introduced in Chapter~\ref{chap:SLCO}.
\SLCO is a DSML for the specification of systems consisting of objects that operate in parallel and communicate with each other.
In \SLCO, such systems can be specified on various levels of abstraction.
From a given \SLCO model on a high level of abstraction, different compositions of model transformations are used to generate NQC~\cite{Baum2003} models for execution on Lego Mindstorms controllers, POOSL~\cite{Theelen2007} models for simulation, and Promela models for formal verification using the model checker SPIN~\cite{Holzmann2003}.
The transformations from \SLCO to these languages are described in Section~\ref{sec:slco:exogenous}.
The part of \SLCO used for the specification of high-level models and the three target languages have different properties, and therefore, several semantic gaps need to be bridged~\cite{Amstel2008}, which are described in Section~\ref{sec:slco:language-gaps}.
Each of these gaps is bridged by one or more model transformations that add implementation details to the original \SLCO model, resulting in a refined \SLCO model that is closer to one of the target languages.
To improve the reusability of these transformations and to deal with only one language for the majority of the correctness proofs, we only use endogenous transformations for the refinement of models, instead of exogenous ones~\cite{Mens:2006:TMT:1706639.1706924}.
These endogenous transformations are described in Section~\ref{sec:slco:endogenous}.
To be able to use endogenous transformations for refinement, we extended \SLCO with constructs to specify systems on a lower level of abstraction too.

\begin{figure}[hbt]
\centering
\includegraphics[width=.7\textwidth]{reusable-correct-transformations/figs/sequences}
\caption{Sequences of transformations for three target languages}
\label{fig:reusable-correct-transformations:sequences}
\end{figure}

Figure~\ref{fig:reusable-correct-transformations:sequences} schematically depicts a number of composed model transformations that transform an \SLCO model to various target languages.
The arrows inside the dashed shape depict endogenous transformations that transform \SLCO models into more refined \SLCO models.
Each of the endogenous transformations leads to a model with observationally equivalent behavior.
The arrows across the border of the dashed shape depict exogenous transformations.
Because the semantic gaps between \SLCO and the target languages are bridged completely by the endogenous transformations, these exogenous transformations are straightforward translations of \SLCO constructs into equivalent constructs in the target languages.
By developing sequences of endogenous transformations that are as fine-grained as possible, we improve the reusability of the individual transformations within sequences and reduce the number of complicated proofs.

In this chapter, we discuss how the transformations of \SLCO models to the three target languages are decomposed into sequences of transformations,
and the way these transformations are composed and reused within the sequences.
Furthermore, we describe a formal framework for \SLCO used to reason about the correctness of model transformations.
First, the formal structural operational semantics (SOS)~\cite{SOS2004Plotkin} of \SLCO is defined, which generates a labeled transition system~(LTS) representation of the dynamics of an \SLCO model.
The semantics described in this chapter are based on our experience with the executable prototype described in Chapter~\ref{chap:prototype-semantics} and describe the behavior of an \SLCO model in terms of the behavior of the individual transitions of state machines in the model.
Second, for each transformation, a (behavioral) equivalence relation is established between the behavior of an \SLCO model before and after transformation.
Finally, a proof of the correctness of a transformation is given by showing that the transformation preserves the corresponding equivalence relation.

The benefits of this approach are manifold.
The correctness of the aforementioned model transformations is proven in general, not only for particular model instances.
The use of SOS and the behavioral equivalence relations allows us to focus only on the part of a model affected by a transformation when reasoning about the correctness of this transformation.
%Here, additional benefits of fine-grained transformations are evident, since they allow for rather straightforward proofs.
Furthermore, the constraints on input models required for some of the transformations, detected earlier during experimental work, can now be formally shown necessary for the correctness of the transformations.
This proves that a sequence of transformations is well-composed if each of the intermediate models satisfies the constraints that must hold for the transformation that is applied next.

The remainder of this chapter is structured as follows.
In Section~\ref{sec:reusable-correct-transformations:model_transformations}, the model transformations related to \SLCO and the way they are reused are described.
The correctness criterion and a proof of one of the transformations are given in Section~\ref{sec:reusable-correct-transformations:correctness_of_transformations}.
This section also describes the formal semantics of \SLCO, which is required for the proof.
Section~\ref{sec:reusable-correct-transformations:related_work} discusses the related work,
and Section~\ref{sec:reusable-correct-transformations:conclusions} concludes this chapter.