---
# System prepended metadata

title: TurtleCoin v2

---

# TurtleCoin v2
Design doc for TurtleCoin Core Suite v2

# Article Introduction
*Forward by RockSteady*

In the early days of TurtleCoin, at least two forevers ago, we blew the dust off a legacy Bytecoin codebase and launched a coin using just enough special sauce to call TurtleCoin our own, all on a whim. As a new network, there were the usual struggles, like when ASIC for CryptoNote emerged, or when we found a pretty serious RPC issue in Simplewallet. As our team and their contributions grew, we eventually found ourselves in a new codebase, rock solid, but still carrying the scars of our past.

Fast forward to now, we are 3 million blocks wiser, our team is many lines of code more experienced, and as we have chiseled our way through, we made a list of a some areas where we can do better. Taking a step back, the last few years have shown us that we are reaching the limit of our current software, and the time is now for us to think radically different and put something new on the table. It is time to build something of our own.

With great respect and thanks to the CryptoNote family, Forknote, Bytecoin, and those who enabled us to get where we are now, we humbly begin our own path and embark on a new journey. What we produce next will be from scratch, written by us, exactly how we have always wanted it.

TurtleCoin v2 is the future, and we are excited to share it with you! 

## The Goal

We aim to redesign TurtleCoin from the ground up to avoid the mistakes of the past while putting an eye to the future state of the network. This is accomplished by replacing traditional Proof of Work (PoW) based blockchain mechanisms with a round-based hybrid Proof of Stake (PoS)/PoW model. This document describes the fundamentals required for network operation, how nodes interact with each other, and how such services are presented for end-user consumption.

### Proof of Work (PoW)

The traditional approach to cryptocurrency networks is to deploy a PoW model such that miners perform endless repetitive hashing of block data searching for a hash that meets a set difficulty. The miner is rewarded for burning fossil fuels via the a specially constructed transaction (the "coinbase transaction") that allows the miner to create new funds as a result of claiming that block.

### Proof of Stake (PoS)

PoS deviates from the PoW model in that PoW is no longer performed, instead passing the torch to block producers (the "producers") whose work is then validated by the block validators (the "validators"). These parties are typically elected via users staking, or otherwise backing, their preferred candidates for those roles. Selection of producers and validators typically takes place via an election mechanism as part of the consensus rules.

### Our Vision, Round Based Hybrid PoS w/ PoW

Combine the best of PoW with the stability and speed of PoS to create one kick ass network. We'll use PoS for managing the distributed ledger and users will submit PoW with each transaction.

#### It works like this..

When a user wishes to send a transaction, they generate the transaction in the "normal" way. However, there is a nonce field included in the transaction that allows for the user to perform PoW for that singular transaction to meet a preset difficulty for transactions. The resulting transaction and the nonce is then forwarded to a node for broadcast to the network.

Every transaction will require a base amount of work (PoW) before it can be submitted to the network in addition to a fee-per-byte network transaction fee. However, if a user wishes to prioritize their transaction on the network they have two options.

1) Pay a higher network transaction fee
2) Perform PoW that meets a higher difficulty requirement

By completing either 1 or 2 above (or both) their transaction will be prioritized by the network ahead of baseline transactions.

**Note:** Fusion transactions will no longer exist on the network. As a wise man once said, "ass, cash, or PoW, no one rides for free". Everyone pays their fair share for transacting on the network regardless of the reason for that transaction.

Once a transaction is received by a node, the node performs basic checks (ie. transaction construction, valid nonce, PoW meets required difficulty, verifies signatures, etc). Once that node completes the basic verification, it forwards the transaction to the rest of the network including the producers. Producers hold the transactions in the global memory pool after performing their own validations of the transaction ensuring that it is indeed a valid transaction. At this point, users can presume some level of assurance that the transaction will be committed to a block solely because the producers have accepted the transaction into the pool.

Once enough PoW transactions have accumulated in the pool to satisify the network difficulty, the then current producer creates a block that ratifies the selection of transactions necessary to meet (or exceed) the network difficulty requirement. When doing so, the producer creates a block reward equivalent, 1 for 1 matching the aggregate transaction fees included in the block.

**Note:** This means that emission is directly tied to the actual use of the network as a transactional platform. We will no longer be emitting currency on a pre-defined schedule as a result of this change. The more the network is used, the more currency that will become available.

The block reward is distributed proportionately between the block producer, the validators, and a subset of the users who staked that producer. Upon completion of the block the block is signed by the producer and transmitted to the network.

The validators, upon receiving the block, validate (at minimum) that:

- the producer was permitted to produce the block (their turn)
- enough PoW transactions have been included to meet network difficulty
- transaction hashes included in the block have been included such that the hashes are arranged in descending order
- the block is properly signed by the producer
- the transactions in the block meet all of the consensus rules of the network (no double spends, etc); and
- no unnessecary data is included in the block
- that the producer claimed and paid out the proper block rewards.

A minimum of 51% of the validators must then sign the block and submit their signatures to the network thus ratifiying the block itself.

After the block is ratified, the network difficulty is adjusted (if necessary) to account for things such as the number of transactions included, the PoW of transactions included, and any other metrics required to keep the network operating correctly.

#### Roll that beautiful storage saving feature...

One of the largest benefits in this scenario is that we no longer produce **empty** blocks and thus save tons of storage space.

#### Tut, Tut

In addition, each block's reward is distributed to multiple recipients via the payments to the producer, a psuedo random validator, and a random subset of users who have staked the given producer and validator.

##### The Reward Split

* 20% to the producer of the block
* 20% to the one of the validators of the block
* 30% to the users who staked the producer
    * Maximum of 10 randomly selected stakers
* 30% to the users who staked the validator
    * Maximum of 10 randomly selected stakers

### Becoming a Block Producer / Validator

A user ("Alice") wishing to operate a block producer or validator "announces" their intent for candidacy by staking their node(s) with a minimum stake of `X` TRTL. Upon successfully staking their node, Alice's node is thereby a candidate for either a producer or validator spot in a round. However, it is important to note that does not automatically make Alice a block producer or a validator.

To be a candidate for either role within the network, Alice must be "endorsed" by other users of the network via users staking their funds in support of Alice. Once Alice has at least 1 TRTL staking her, she is now a viable candidate for a producer or validator spot.

**Note:** The details of how these stakes are sent, recorded, etc. are in progress and details will come later.

### Electing Producers & Validators

First, we take the hashes of every block in the now closed round $\{B_1, B_2, B_3, ...\}$ and calculate the merkle root for those hashes to establish $M$ as the election seed for the next round.

We then take $M$ and convert that to a scalar $p$:

$p = H_s(M)$

Then compute the public key $P$ of $p$:

$P = pG$

We then tally `T` the individual bytes of `S` to determine if the result is odd or even.

$T = \{S_1 + S_2 + \dots\} \mod 2$

* If $T$ is odd ($T \equiv 1$) we collect public keys from the candidates list that are $>= P$. 
* If $T$ is even ($T \equiv 0$), we collect public keys from the candidates list that are $< P$.

Once the collection of public keys in the new defined range have been collected. We review the number of votes (stakes) received for each public key and construct a listing of canidates with their tally of active votes. The list is then sorted by vote count in ascending order and the top and bottom candidate of the results are discarded. The total votes submitted for the remaining candidates are then tallied to arrive at a total votes casted count ($V$).

The resulting candidates are then assigned ranges for which the selection algorithm must land for them to become a producer/validator.

If the remaining candidates consist of:
```
Candidate 1: 11,583 votes
Candidate 2: 25,749 votes
Candidate 3: 99,000 votes
Candidate 4: 127,342 votes
```
The the ranges for each node are as follows:
```
Candidate 1: 0 - 11583
Candidate 2: 11,584 - 25,749
Candidate 3: 25,750 - 99,000
Candidate 4: 99,001 - 127,342
```

We then perform the seletion of the first producer via $e_1 = p \mod V$. The value of $e_1$ is compared against the node ranges thereby establshing that node as a producer.

On the next iteration of the election process, the previously selected node ($e_n$) is removed from the collection and $V$ is recomputed before the selection algorithm runs again. Thereby guaranteeing that we do not elect the same producer/validator into more than one round slot.

The process is repeated until the required number of producers (more detail later) have been selected for the next round. At which point, the same process is performed for the candidates on the oppposite side of $P$ as $T$ had dictated for producers until we have selected enough validators for the next round.

In the event that we are unable to select the necessary number of producers or validators as required for the round (ie. there are less canidates than there are required slots) the number of required producers/validators will be decreased until there are enough candidates to fulfill the request; however, at no point shall the number of producers and/or stakers for a round be an even number of spots.

### Random Staker / Validator Selection (for Block Rewards)

When a block is produced, the producer must include relevants outputs to not only pay themselves but to also pay a deterministicially selected validator as well as stakers that staked the producer **and** that validator.

To select who receives the reward(s) we perform the same selection alogirthm logic as we do for producers and validators with the exception that the prior block hash is used in place of the merkle root for the previous round ($M$).

In the case of selecting which validator gets rewarded, the process is ran exactly once (1) for the set of validators for that round.

For determining the stakers to reward, the process is completed exactly ten (10) times for the set of stakers staking the winning producer/validator and the number of stakes the staker has submitted for the given candidate determine their "vote count". 

If, any time during the loop used in selecting stakers, the number of available stakers is exhausted (there are less than 10 stakers that backed that producer/validator), the process resumes as if all stakers are included in pool again and the iteration(s) continue until the necessary ten (10) stakers are identified for reward.

After completing the above, the producer then constructs a transaction for inclusion in the block that rewards the parties in the percentages necessary such that there are twenty-two (22) outputs in the miner transaction that is included in the block.

* 1 for the producer
* 1 for the selected validator
* 1 each for the 10 stakers of producer
* 1 each for the 10 stakers of validator

The entire process is designed with a sense of psuedo-randomness that can be recreated by every node on the network using the defined process. In essence, the whole reward structure is a bit of an election with an upper and lower house as well as a lottery for those that backed the elected producer/validator.

## The Issues in a Nutshell...

### Relaunch

**Problem:** The current blockchain is very, very, very big, and growing every day whether transactions are included in blocks or not. There is also an insane amount of bloat in the chain including transactional spam (fusions anyone?), CantiPixels, and gobs of other useless data that is like walking around with cement shoes with two boat anchors tied chained to your ankles.

**Solution:** Relaunch the chain. Out with the old and in with the new. To facilitiate this, we're going to need to let the coins on the old network *burn* in a provable way to prevent errant inflation or other nefarious incidents. In addition, the old chain must be spun down in such a way that the chain officially ends at a certain block. Users need a way to transfer their funds from the old chain to the new chain and that means we're going to need a...

### Coin Swap

**Problem:** We have to efficiently move funds from the old chain to the new chain.

**Solution:** A coin swap window of opportunity. The coin swap window to the new chain will be 1,000,000 blocks (as measured by the old chain) during which time users will submit transactions on the old chain to a predetermined wallet address that will serve as a burn address whereby no one user can pick up the funds out of that address (this will be a multisig `N:N` wallet to make sure no one party controls it). An outside watcher server will watch for transactions on the old chain going to that wallet as instructed by the swap "service", and release funds on the new chain to the address/keys provided by the user. The swap itself will be funded via a pre-mine on the new chain equivalent to the estimated circulating supply at the time of of the end of the old chain.

After the swap window completes, the remainder of the funds left of the premine will be redistributed via normal block rewards as transaction fees on the new chain.

**Note:** The redistribution of any unclaimed (whether through inaction or as "lost" wallets) via block rewards will be executed over a number of rounds on the new chain to attempt to ensure a somewhat even distribution of those funds to producers, validators, and stakers. Details on the exact schedule of distribution will come later as it will be highly dependent on how much TRTL will have to be dealt with.

In short, the swap mechanism will be a website that helps you transition from old coins to new coins. The technical mechanics of which will be discussed in later articles.

Wait... the chain is massive... we can't just carry over everything from old to new we have to think about...

### Swapping 107,198,508+ Outputs...

**Problem:** Swapping over 100M outputs to the new chain is... let's put it simply, *incredibly stupid*. If we were to do that, yes, the new chain would not have the *history* of all of those outputs, but considering that we don't know which outputs are still spendable, there is an unknown number of outputs that we have to create on the new chain as part of the swap process. That number is somewhere between `0` and `107,198,508` (as of the time of this writing). That's just insane not only to think about but to also execute on.

**Solution:** During the relaunch of the network and required coin swap, we will performing the equivalent of a 100,000:1 (atomic units) swap while maintaining two decimal places. Swaps of less than 1,000 TRTL will simply become dust and will not be swappable. Don't worry though, the swap "service" will gladly take your unoptimized outputs and give you brand spanking new optimized outputs.

***This swap ratio will eliminate the need to transfer more than ~81% (as of the time of this writing) of the outputs on the old chain thereby avoiding the pollution of the new chain with much of the  problems that exist with the current chain.***

##### A Note Swap Transaction Fees

The swap service will be set up such that as long as 100% of the funds in a transaction sent to the swap service are actually sent to the swap service (no change outputs) then all network transaction fees you pay to send those coins to the swap service will be included in the amount that you receive on the new chain. Furthermore, the swap service will have the ability to bypass the new chain transaction fee mechanics so that you receive the full value of your swapped funds at the ratio given (truncated to two decimals).

### Removal of the Total Supply Cap

Given the fact that we will no longer be emitting empty blocks (and thus there is no defined block schedule), there is no good way to determine an emission schedule to reach a maximum coin supply with any reasonable certainty. Also given that coin emission will be directly tied to network use to determine block rewards, the total supply cap of the new chain (previously reported as 10,000,000 TRTL) will be removed entirely. This means that use of the network not only dictates block rewards but also dictates the total supply of the network.










<!---- END ARTICLE ABOVE THIS LINE -->

## Software
As you may be used to with our current software, the different functions are divided up into different programs. One program connects you to the network, and a different one is your basic command line wallet. This was done originally to keep the two spaces separate codewise, and for the sake of security. That still makes sense, so we kept more or less the same structure we had before of daemon-and-a-wallet.

### Daemon 
The daemon is the connection to the network. Its job is to connect to peers, sync, and verify transactions. 

- Can connect to P2P network
- Maintains a list of peers
- Fetch data for wallets


### User Wallet
The user wallet is in charge of managing keys, creating and verifying transactions. 
- Can generate keys
- Can sign, verify signatures
- Can request transactions by hash from daemon
- Can create, verify transactions

#### Wallet ops
- **GET** /wallets # return all wallet addresses as objects
- **GET** /wallets/balance # return balance with address objects
- **GET** /wallets/balance/{address} # return balance of specific address
- **GET** /wallets/transactions/{address} # return transactions for specific address
- **GET**  /wallet/create # create a new wallet and keys
- **POST** /wallet/import # import wallet keys via JSON

#### Credentials
- **GET** /keys/{address} # get keys for a specific wallet
- **GET** /keys/export/{address} # get keys as a file keys-{date}.backup

#### Utilities
- **GET** /status/wallet # status of the wallet
- **GET** /status/node # status of the node we are connected to
- **GET** /validate/{address} # validate a v2 TRTL address
- **GET** /save # write wallet data to disk

