# Cost accounting specification

## Summary

In order to protect from DOS attack we charge for the execution of the rholang program. Interpreting Rholang programs consists of:

- lexing and parsing
- normalizing the program
- reducing the program

There are possible DOS attacks at each of these steps:

- Lexer/Parser:
- One can write a big program that will cause lexer/parser to stack overflow.

- Normalizer:
- Structuring the program in such a way that during normalizing the AST we run into stack overflow.

- Reducer:
- Again, it is possible to structure a program in such a way that the reduction will throw StackOverflow error.
- Building a program that costs more to execute than provided phlogiston limit.

### Current obstacles

We don't control the lexer/parser parts yet, so it's still possible to provide a program that won't fit into memory. We need to control these parts as well in a manner that doesn't risk with stack overflow errors (executing in the stack-safe monad). We also might investigate whether it's possible to assess if provided phlo limit is sufficient during lexing/parsing.

### Questions

- Should we charge for lexer/parser phase?

- Should we charge for normalizer phase?

## Business requirements

- Stop program execution when deployment runs out of phlos. If it's not possible to do immediately, do it as soon as possible.
- Charge for execution of the rholang program.
- Charge for storage of the rholang program in the tuplespace.

## Technical requirements

- Given that rholang interpreter is multi-threaded and the phlo limit is global we need to share and update its state correctly.
There are multiple types of errors that can be throw during the interpretation. Program errors are not "fatal", in a sense that they don't interrupt the deployment's execution - they cause a deployment to error and are reported at the end but they don't interrupt reduction of other terms in the deployment.

needs to be fatal. It must stop the execution of other terms in the deployment:`OutOfPhlogistonError`

term1 | term2 | term3

If we run out of phlogistons during reducing,`term1`

and`term2`

need to be stopped as soon as possible. We don't want to make more work that user is willing to pay for.`term3`

## Interpreter phases and cost accounting

### Lexer/Parser

We don't charge during this phase.

### Normalizer

We don't charge during this phase.

### Reducer

Reducer is where the magic happens, it's the workhorse of the rholang interpreter. We charge for every _meaningful_ operation.

From the cost accounting perspective, reduction of the rholang program is one of the following:

1. Evaluating a term.

2. Substituting variables in the term.

3. Spatial match algorithm.

4. Methods called on rholang terms.

5. Interaction with RSpace.

#### Evaluating a term

We charge constant cost for evaluating a term like: send, receive, method call, variable. This is a constant cost for which order is the same as basic methods like nth method call, keys etc.

#### Substitution

Substitution is the process where we substitute bound variables with the environment variables they bind to. This process can either succeed or fail (failing to substitute is an error but we charge nevertheless). The cost of substitution is:

- for success cost proportional to the byte size of the substitute term

- for failure cost proportional to the byte size of the original term

#### Spatial match

Spatial match is a powerful feature of rholang which allows to write complex match between rholang terms and patterns. The more complex the ** (term, pattern)** pair is the more expensive it is to compute the match.

For example

3 matches 1

is simple, both ** 3** and

**are**

`1`

*concrete*terms so they can be compared using plain java equivalence,

match 3 { 2 \/ 1 => â€¦ }

is more expensive because it involves *logical connective* **AND**. This means that the algorithm needs to check that all of the branches of the connective satisfy the predicate.

match 3 \/ 4 { ~2 /\ ~1 => â€¦ }

is even more complex because we need to check all the permutations of terms and patterns.

Matching can quickly become complex as the more complex patterns and/or terms are being matched against each other. General idea behind cost accounting is that we charge for making an actual comparison between terms:

- in
we will charge for comparing channels and data`@x!(10) matches @y!(11)`

- in
we will charge for comparing respective elements of the lists against each other`[1,2,3] matches [=x, =y, =z]`

- etc.

so the more ** (term, pattern)** comparisons match requires the more expensive it is. The actual cost of comparing term against pattern is proportional to the byte size of the smaller object. This is based on the java equality method.

#### Methods

nth | toByteArray | hexToBytes | toUtf8Bytes | union | diff | add | delete | contains | get | getOrElse | set | keys | size | length | slice | append | interpolate | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|

List | C | -- | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | C | proportional to value of higher index | proportional to the length of underlying string | n/a |

GByteArray | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | na | n/a | n/a | n/a | n/a | n/a | n/a | proportional to value of higher index | proportional to the logarithm of length of target byte array | n/a |

Tuple | C | -- | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a |

Set | n/a | -- | n/a | n/a | proportional to the size of collection that is an argument method | proportional to the size of collection that is an argument method | C | C | C | n/a | n/a | n/a | n/a | proportional to the size of base collection on which this method is called. Complexity of the `size` method is `O(n)` | n/a | n/a | same as union | n/a |

Map | n/a | -- | n/a | n/a | proportional to the size of collection that is an argument method | proportional to the size of collection that is an argument method | n/a | C | C | C | C | C | C | proportional to the size of base collection on which this method is called. Complexity of the `size` method is `O(n)` | n/a | n/a | same as union | n/a |

any term | n/a | proportional to the byte size of the underlying rholang term | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a |

String | n/a | -- | proportional to the length of underlying string | proportional to the length of underlying string | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | C | proportional to value of higher index | proportional to the sum of the lengths of both strings | proportional to `length_of_string * number_of_entries_in_map` |

- C - constant
- n/a - method not available

#### Interaction with RSpace

Cost accounting for interaction with RSpace has two flavors:

- Charge for storing the term
- Charge for work done required to find a match between `produce` and `consume`.

#### Storage

Before calling ** produce** or

**on RSpace we charge for storing the term. We do that to secure the required phlos for executing the action. If our**

`consume`

**/**

`produce`

**is linear (not persistent) and it finds a match we refund the phlos secured before executing an action. The cost of storage is proportional to the byte size of the term we want to store.**

`consume`

#### Matching

In order to find a match between `produce` and `consume` RSpace runs a spatial match algorithm on supplied bind patterns and data residing on the channel. The spatial match algorithm can be complex (expensive). The nature of the interpreter and RSpace (see Technical details section) requires making all available phlos (at the moment of interacting with RSpace) the upper limit for the spatial match algorithm triggered in the RSpace. The spatial match algorithm tracks and updates the cost state while it runs. It means that as soon as available phlos are used up in the middle of running the match we will short circuit and do not try matching anymore.

Upon leaving the RSpace we charge with the amount of phlos used in the RSpace or, if RSpace returns `OutOfPhlos`

error, we zero the cost accounting state.

## Technical details of the cost accounting in the interpreter

TODO