The World's Leading Bitcoin ATM Operator CoinFlip

FlowCards: A Declarative Framework for Development of Ergo dApps

FlowCards: A Declarative Framework for Development of Ergo dApps
Introduction
ErgoScript is the smart contract language used by the Ergo blockchain. While it has concise syntax adopted from Scala/Kotlin, it still may seem confusing at first because conceptually ErgoScript is quite different compared to conventional languages which we all know and love. This is because Ergo is a UTXO based blockchain, whereas smart contracts are traditionally associated with account based systems like Ethereum. However, Ergo's transaction model has many advantages over the account based model and with the right approach it can even be significantly easier to develop Ergo contracts than to write and debug Solidity code.
Below we will cover the key aspects of the Ergo contract model which makes it different:
Paradigm
The account model of Ethereum is imperative. This means that the typical task of sending coins from Alice to Bob requires changing the balances in storage as a series of operations. Ergo's UTXO based programming model on the other hand is declarative. ErgoScript contracts specify conditions for a transaction to be accepted by the blockchain (not changes to be made in the storage state as result of the contract execution).
Scalability
In the account model of Ethereum both storage changes and validity checks are performed on-chain during code execution. In contrast, Ergo transactions are created off-chain and only validation checks are performed on-chain thus reducing the amount of operations performed by every node on the network. In addition, due to immutability of the transaction graph, various optimization strategies are possible to improve throughput of transactions per second in the network. Light verifying nodes are also possible thus further facilitating scalability and accessibility of the network.
Shared state
The account-based model is reliant on shared mutable state which is known to lead to complex semantics (and subtle million dollar bugs) in the context of concurrent/ distributed computation. Ergo's model is based on an immutable graph of transactions. This approach, inherited from Bitcoin, plays well with the concurrent and distributed nature of blockchains and facilitates light trustless clients.
Expressive Power
Ethereum advocated execution of a turing-complete language on the blockchain. It theoretically promised unlimited potential, however in practice severe limitations came to light from excessive blockchain bloat, subtle multi-million dollar bugs, gas costs which limit contract complexity, and other such problems. Ergo on the flip side extends UTXO to enable turing-completeness while limiting the complexity of the ErgoScript language itself. The same expressive power is achieved in a different and more semantically sound way.
With the all of the above points, it should be clear that there are a lot of benefits to the model Ergo is using. In the rest of this article I will introduce you to the concept of FlowCards - a dApp developer component which allows for designing complex Ergo contracts in a declarative and visual way.
From Imperative to Declarative
In the imperative programming model of Ethereum a transaction is a sequence of operations executed by the Ethereum VM. The following Solidity function implements a transfer of tokens from sender to receiver . The transaction starts when sender calls this function on an instance of a contract and ends when the function returns.
// Sends an amount of existing coins from any caller to an address function send(address receiver, uint amount) public { require(amount <= balances[msg.sender], "Insufficient balance."); balances[msg.sender] -= amount; balances[receiver] += amount; emit Sent(msg.sender, receiver, amount); } 
The function first checks the pre-conditions, then updates the storage (i.e. balances) and finally publishes the post-condition as the Sent event. The gas which is consumed by the transaction is sent to the miner as a reward for executing this transaction.
Unlike Ethereum, a transaction in Ergo is a data structure holding a list of input coins which it spends and a list of output coins which it creates preserving the total balances of ERGs and tokens (in which Ergo is similar to Bitcoin).
Turning back to the example above, since Ergo natively supports tokens, therefore for this specific example of sending tokens we don't need to write any code in ErgoScript. Instead we need to create the ‘send’ transaction shown in the following figure, which describes the same token transfer but declaratively.
https://preview.redd.it/id5kjdgn9tv41.png?width=1348&format=png&auto=webp&s=31b937d7ad0af4afe94f4d023e8c90c97c8aed2e
The picture visually describes the following steps, which the network user needs to perform:
  1. Select unspent sender's boxes, containing in total tB >= amount of tokens and B >= txFee + minErg ERGs.
  2. Create an output target box which is protected by the receiver public key with minErg ERGs and amount of T tokens.
  3. Create one fee output protected by the minerFee contract with txFee ERGs.
  4. Create one change output protected by the sender public key, containing B - minErg - txFee ERGs and tB - amount of T tokens.
  5. Create a new transaction, sign it using the sender's secret key and send to the Ergo network.
What is important to understand here is that all of these steps are preformed off-chain (for example using Appkit Transaction API) by the user's application. Ergo network nodes don't need to repeat this transaction creation process, they only need to validate the already formed transaction. ErgoScript contracts are stored in the inputs of the transaction and check spending conditions. The node executes the contracts on-chain when the transaction is validated. The transaction is valid if all of the conditions are satisfied.
Thus, in Ethereum when we “send amount from sender to recipient” we are literally editing balances and updating the storage with a concrete set of commands. This happens on-chain and thus a new transaction is also created on-chain as the result of this process.
In Ergo (as in Bitcoin) transactions are created off-chain and the network nodes only verify them. The effects of the transaction on the blockchain state is that input coins (or Boxes in Ergo's parlance) are removed and output boxes are added to the UTXO set.
In the example above we don't use an ErgoScript contract but instead assume a signature check is used as the spending pre-condition. However in more complex application scenarios we of course need to use ErgoScript which is what we are going to discuss next.
From Changing State to Checking Context
In the send function example we first checked the pre-condition (require(amount <= balances[msg.sender],...) ) and then changed the state (i.e. update balances balances[msg.sender] -= amount ). This is typical in Ethereum transactions. Before we change anything we need to check if it is valid to do so.
In Ergo, as we discussed previously, the state (i.e. UTXO set of boxes) is changed implicitly when a valid transaction is included in a block. Thus we only need to check the pre-conditions before the transaction can be added to the block. This is what ErgoScript contracts do.
It is not possible to “change the state” in ErgoScript because it is a language to check pre-conditions for spending coins. ErgoScript is a purely functional language without side effects that operates on immutable data values. This means all the inputs, outputs and other transaction parameters available in a script are immutable. This, among other things, makes ErgoScript a very simple language that is easy to learn and safe to use. Similar to Bitcoin, each input box contains a script, which should return the true value in order to 1) allow spending of the box (i.e. removing from the UTXO set) and 2) adding the transaction to the block.
If we are being pedantic, it is therefore incorrect (strictly speaking) to think of ErgoScript as the language of Ergo contracts, because it is the language of propositions (logical predicates, formulas, etc.) which protect boxes from “illegal” spending. Unlike Bitcoin, in Ergo the whole transaction and a part of the current blockchain context is available to every script. Therefore each script may check which outputs are created by the transaction, their ERG and token amounts (we will use this capability in our example DEX contracts), current block number etc.
In ErgoScript you define the conditions of whether changes (i.e. coin spending) are allowed to happen in a given context. This is in contrast to programming the changes imperatively in the code of a contract.
While Ergo's transaction model unlocks a whole range of applications like (DEX, DeFi Apps, LETS, etc), designing contracts as pre-conditions for coin spending (or guarding scripts) directly is not intuitive. In the next sections we will consider a useful graphical notation to design contracts declaratively using FlowCard Diagrams, which is a visual representation of executable components (FlowCards).
FlowCards aim to radically simplify dApp development on the Ergo platform by providing a high-level declarative language, execution runtime, storage format and a graphical notation.
We will start with a high level of diagrams and go down to FlowCard specification.
FlowCard Diagrams
The idea behind FlowCard diagrams is based on the following observations: 1) An Ergo box is immutable and can only be spent in the transaction which uses it as an input. 2) We therefore can draw a flow of boxes through transactions, so that boxes flowing in to the transaction are spent and those flowing out are created and added to the UTXO. 3) A transaction from this perspective is simply a transformer of old boxes to the new ones preserving the balances of ERGs and tokens involved.
The following figure shows the main elements of the Ergo transaction we've already seen previously (now under the name of FlowCard Diagram).
https://preview.redd.it/9kcxl11o9tv41.png?width=1304&format=png&auto=webp&s=378a7f50769292ca94de35ff597dc1a44af56d14
There is a strictly defined meaning (semantics) behind every element of the diagram, so that the diagram is a visual representation (or a view) of the underlying executable component (called FlowCard).
The FlowCard can be used as a reusable component of an Ergo dApp to create and initiate the transaction on the Ergo blockchain. We will discuss this in the coming sections.
Now let's look at the individual pieces of the FlowCard diagram one by one.
  1. Name and Parameters
Each flow card is given a name and a list of typed parameters. This is similar to a template with parameters. In the above figure we can see the Send flow card which has five parameters. The parameters are used in the specification.
  1. Contract Wallet
This is a key element of the flow card. Every box has a guarding script. Often it is the script that checks a signature against a public key. This script is trivial in ErgoScript and is defined like the def pk(pubkey: Address) = { pubkey } template where pubkey is a parameter of the type Address . In the figure, the script template is applied to the parameter pk(sender) and thus a concrete wallet contract is obtained. Therefore pk(sender) and pk(receiver) yield different scripts and represent different wallets on the diagram, even though they use the same template.
Contract Wallet contains a set of all UTXO boxes which have a given script derived from the given script template using flow card parameters. For example, in the figure, the template is pk and parameter pubkey is substituted with the `sender’ flow card parameter.
  1. Contract
Even though a contract is a property of a box, on the diagram we group the boxes by their contracts, therefore it looks like the boxes belong to the contracts, rather than the contracts belong to the boxes. In the example, we have three instantiated contracts pk(sender) , pk(receiver) and minerFee . Note, that pk(sender) is the instantiation of the pk template with the concrete parameter sender and minerFee is the instantiation of the pre-defined contract which protects the miner reward boxes.
  1. Box name
In the diagram we can give each box a name. Besides readability of the diagram, we also use the name as a synonym of a more complex indexed access to the box in the contract. For example, change is the name of the box, which can also be used in the ErgoScript conditions instead of OUTPUTS(2) . We also use box names to associate spending conditions with the boxes.
  1. Boxes in the wallet
In the diagram, we show boxes (darker rectangles) as belonging to the contract wallets (lighter rectangles). Each such box rectangle is connected with a grey transaction rectangle by either orange or green arrows or both. An output box (with an incoming green arrow) may include many lines of text where each line specifies a condition which should be checked as part of the transaction. The first line specifies the condition on the amount of ERG which should be placed in the box. Other lines may take one of the following forms:
  1. amount: TOKEN - the box should contain the given amount of the given TOKEN
  2. R == value - the box should contain the given value of the given register R
  3. boxName ? condition - the box named boxName should check condition in its script.
We discuss these conditions in the sections below.
  1. Amount of ERGs in the box
Each box should store a minimum amount of ERGs. This is checked when the creating transaction is validated. In the diagram the amount of ERGs is always shown as the first line (e.g. B: ERG or B - minErg - txFee ). The value type ascription B: ERG is optional and may be used for readability. When the value is given as a formula, then this formula should be respected by the transaction which creates the box.
It is important to understand that variables like amount and txFee are not named properties of the boxes. They are parameters of the whole diagram and representing some amounts. Or put it another way, they are shared parameters between transactions (e.g. Sell Order and Swap transactions from DEX example below share the tAmt parameter). So the same name is tied to the same value throughout the diagram (this is where the tooling would help a lot). However, when it comes to on-chain validation of those values, only explicit conditions which are marked with ? are transformed to ErgoScript. At the same time, all other conditions are ensured off-chain during transaction building (for example in an application using Appkit API) and transaction validation when it is added to the blockchain.
  1. Amount of T token
A box can store values of many tokens. The tokens on the diagram are named and a value variable may be associated with the token T using value: T expression. The value may be given by formula. If the formula is prefixed with a box name like boxName ? formula , then it is should also be checked in the guarding script of the boxName box. This additional specification is very convenient because 1) it allows to validate the visual design automatically, and 2) the conditions specified in the boxes of a diagram are enough to synthesize the necessary guarding scripts. (more about this below at “From Diagrams To ErgoScript Contracts”)
  1. Tx Inputs
Inputs are connected to the corresponding transaction by orange arrows. An input arrow may have a label of the following forms:
  1. [email protected] - optional name with an index i.e. [email protected] or u/2 . This is a property of the target endpoint of the arrow. The name is used in conditions of related boxes and the index is the position of the corresponding box in the INPUTS collection of the transaction.
  2. !action - is a property of the source of the arrow and gives a name for an alternative spending path of the box (we will see this in DEX example)
Because of alternative spending paths, a box may have many outgoing orange arrows, in which case they should be labeled with different actions.
  1. Transaction
A transaction spends input boxes and creates output boxes. The input boxes are given by the orange arrows and the labels are expected to put inputs at the right indexes in INPUTS collection. The output boxes are given by the green arrows. Each transaction should preserve a strict balance of ERG values (sum of inputs == sum of outputs) and for each token the sum of inputs >= the sum of outputs. The design diagram requires an explicit specification of the ERG and token values for all of the output boxes to avoid implicit errors and ensure better readability.
  1. Tx Outputs
Outputs are connected to the corresponding transaction by green arrows. An output arrow may have a label of the following [email protected] , where an optional name is accompanied with an index i.e. [email protected] or u/2 . This is a property of the source endpoint of the arrow. The name is used in conditions of the related boxes and the index is the position of the corresponding box in the OUTPUTS collection of the transaction.
Example: Decentralized Exchange (DEX)
Now let's use the above described notation to design a FlowCard for a DEX dApp. It is simple enough yet also illustrates all of the key features of FlowCard diagrams which we've introduced in the previous section.
The dApp scenario is shown in the figure below: There are three participants (buyer, seller and DEX) of the DEX dApp and five different transaction types, which are created by participants. The buyer wants to swap ergAmt of ERGs for tAmt of TID tokens (or vice versa, the seller wants to sell TID tokens for ERGs, who sends the order first doesn't matter). Both the buyer and the seller can cancel their orders any time. The DEX off-chain matching service can find matching orders and create the Swap transaction to complete the exchange.
The following diagram fully (and formally) specifies all of the five transactions that must be created off-chain by the DEX dApp. It also specifies all of the spending conditions that should be verified on-chain.

https://preview.redd.it/fnt5f4qp9tv41.png?width=1614&format=png&auto=webp&s=34f145f9a6d622454906857e645def2faba057bd
Let's discuss the FlowCard diagram and the logic of each transaction in details:
Buy Order Transaction
A buyer creates a Buy Order transaction. The transaction spends E amount of ERGs (which we will write E: ERG ) from one or more boxes in the pk(buyer) wallet. The transaction creates a bid box with ergAmt: ERG protected by the buyOrder script. The buyOrder script is synthesized from the specification (see below at “From Diagrams To ErgoScript Contracts”) either manually or automatically by a tool. Even though we don't need to define the buyOrder script explicitly during designing, at run time the bid box should contain the buyOrder script as the guarding proposition (which checks the box spending conditions), otherwise the conditions specified in the diagram will not be checked.
The change box is created to make the input and output sums of the transaction balanced. The transaction fee box is omitted because it can be added automatically by the tools. In practice, however, the designer can add the fee box explicitly to the a diagram. It covers the cases of more complex transactions (like Swap) where there are many ways to pay the transaction fee.
Cancel Buy, Cancel Sell Transactions
At any time, the buyer can cancel the order by sending CancelBuy transaction. The transaction should satisfy the guarding buyOrder contract which protects the bid box. As you can see on the diagram, both the Cancel and the Swap transactions can spend the bid box. When a box has spending alternatives (or spending paths) then each alternative is identified by a unique name prefixed with ! (!cancel and !swap for the bid box). Each alternative path has specific spending conditions. In our example, when the Cancel Buy transaction spends the bid box the ?buyer condition should be satisfied, which we read as “the signature for the buyer address should be presented in the transaction”. Therefore, only buyer can cancel the buy order. This “signature” condition is only required for the !cancel alternative spending path and not required for !swap .
Sell Order Transaction
The Sell Order transaction is similar to the BuyOrder in that it deals with tokens in addition to ERGs. The transaction spends E: ERG and T: TID tokens from seller's wallet (specified as pk(seller) contract). The two outputs are ask and change . The change is a standard box to balance transaction. The ask box keeps tAmt: TID tokens for the exchange and minErg: ERG - the minimum amount of ERGs required in every box.
Swap Transaction
This is a key transaction in the DEX dApp scenario. The transaction has several spending conditions on the input boxes and those conditions are included in the buyOrder and sellOrder scripts (which are verified when the transaction is added to the blockchain). However, on the diagram those conditions are not specified in the bid and ask boxes, they are instead defined in the output boxes of the transaction.
This is a convention for improved usability because most of the conditions relate to the properties of the output boxes. We could specify those properties in the bid box, but then we would have to use more complex expressions.
Let's consider the output created by the arrow labeled with [email protected] . This label tells us that the output is at the index 0 in the OUTPUTS collection of the transaction and that in the diagram we can refer to this box by the buyerOut name. Thus we can label both the box itself and the arrow to give the box a name.
The conditions shown in the buyerOut box have the form bid ? condition , which means they should be verified on-chain in order to spend the bid box. The conditions have the following meaning:
  • tAmt: TID requires the box to have tAmt amount of TID token
  • R4 == bid.id requires R4 register in the box to be equal to id of the bid box.
  • script == buyer requires the buyerOut box to have the script of the wallet where it is located on the diagram, i.e. pk(buyer)
Similar properties are added to the sellerOut box, which is specified to be at index 1 and the name is given to it using the label on the box itself, rather than on the arrow.
The Swap transaction spends two boxes bid and ask using the !swap spending path on both, however unlike !cancel the conditions on the path are not specified. This is where the bid ? and ask ? prefixes come into play. They are used so that the conditions listed in the buyerOut and sellerOut boxes are moved to the !swap spending path of the bid and ask boxes correspondingly.
If you look at the conditions of the output boxes, you will see that they exactly specify the swap of values between seller's and buyer's wallets. The buyer gets the necessary amount of TID token and seller gets the corresponding amount of ERGs. The Swap transaction is created when there are two matching boxes with buyOrder and sellOrder contracts.
From Diagrams To ErgoScript Contracts
What is interesting about FlowCard specifications is that we can use them to automatically generate the necessary ErgoTree scripts. With the appropriate tooling support this can be done automatically, but with the lack of thereof, it can be done manually. Thus, the FlowCard allows us to capture and visually represent all of the design choices and semantic details of an Ergo dApp.
What we are going to do next is to mechanically create the buyOrder contract from the information given in the DEX flow card.
Recall that each script is a proposition (boolean valued expression) which should evaluate to true to allow spending of the box. When we have many conditions to be met at the same time we can combine them in a logical formula using the AND binary operation, and if we have alternatives (not necessarily exclusive) we can put them into the OR operation.
The buyOrder box has the alternative spending paths !cancel and !swap . Thus the ErgoScript code should have OR operation with two arguments - one for each spending path.
/** buyOrder contract */ { val cancelCondition = {} val swapCondition = {} cancelCondition || swapCondition } 
The formula for the cancelCondition expression is given in the !cancel spending path of the buyOrder box. We can directly include it in the script.
/** buyOrder contract */ { val cancelCondition = { buyer } val swapCondition = {} cancelCondition || swapCondition } 
For the !swap spending path of the buyOrder box the conditions are specified in the buyerOut output box of the Swap transaction. If we simply include them in the swapCondition then we get a syntactically incorrect script.
/** buyOrder contract */ { val cancelCondition = { buyer } val swapCondition = { tAmt: TID && R4 == bid.id && @contract } cancelCondition || swapCondition } 
We can however translate the conditions from the diagram syntax to ErgoScript expressions using the following simple rules
  1. [email protected] ==> val buyerOut = OUTPUTS(0)
  2. tAmt: TID ==> tid._2 == tAmt where tid = buyerOut.tokens(TID)
  3. R4 == bid.id ==> R4 == SELF.id where R4 = buyerOut.R4[Coll[Byte]].get
  4. script == buyer ==> buyerOut.propositionBytes == buyer.propBytes
Note, in the diagram TID represents a token id, but ErgoScript doesn't have access to the tokens by the ids so we cannot write tokens.getByKey(TID) . For this reason, when the diagram is translated into ErgoScript, TID becomes a named constant of the index in tokens collection of the box. The concrete value of the constant is assigned when the BuyOrder transaction with the buyOrder box is created. The correspondence and consistency between the actual tokenId, the TID constant and the actual tokens of the buyerOut box is ensured by the off-chain application code, which is completely possible since all of the transactions are created by the application using FlowCard as a guiding specification. This may sound too complicated, but this is part of the translation from diagram specification to actual executable application code, most of which can be automated.
After the transformation we can obtain a correct script which checks all the required preconditions for spending the buyOrder box.
/** buyOrder contract */ def DEX(buyer: Addrss, seller: Address, TID: Int, ergAmt: Long, tAmt: Long) { val cancelCondition: SigmaProp = { buyer } // verify buyer's sig (ProveDlog) val swapCondition = OUTPUTS.size > 0 && { // securing OUTPUTS access val buyerOut = OUTPUTS(0) // from [email protected] buyerOut.tokens.size > TID && { // securing tokens access val tid = buyerOut.tokens(TID) val regR4 = buyerOut.R4[Coll[Byte]] regR4.isDefined && { // securing R4 access val R4 = regR4.get tid._2 == tAmt && // from tAmt: TID R4 == SELF.id && // from R4 == bid.id buyerOut.propositionBytes == buyer.propBytes // from script == buyer } } } cancelCondition || swapCondition } 
A similar script for the sellOrder box can be obtained using the same translation rules. With the help of the tooling the code of contracts can be mechanically generated from the diagram specification.
Conclusions
Declarative programming models have already won the battle against imperative programming in many application domains like Big Data, Stream Processing, Deep Learning, Databases, etc. Ergo is pioneering the declarative model of dApp development as a better and safer alternative to the now popular imperative model of smart contracts.
The concept of FlowCard shifts the focus from writing ErgoScript contracts to the overall flow of values (hence the name), in such a way, that ErgoScript can always be generated from them. You will never need to look at the ErgoScript code once the tooling is in place.
Here are the possible next steps for future work:
  1. Storage format for FlowCard Spec and the corresponding EIP standardized file format (Json/XML/Protobuf). This will allow various tools (Diagram Editor, Runtime, dApps etc) to create and use *.flowcard files.
  2. FlowCard Viewer, which can generate the diagrams from *.flowcard files.
  3. FlowCard Runtime, which can run *.flowcard files, create and send transactions to Ergo network.
  4. FlowCard Designer Tool, which can simplify development of complex diagrams . This will make designing and validation of Ergo contracts a pleasant experience, more like drawing rather than coding. In addition, the correctness of the whole dApp scenario can be verified and controlled by the tooling.
submitted by Guilty_Pea to CryptoCurrencies [link] [comments]

FlowCards: A Declarative Framework for Development of Ergo dApps

FlowCards: A Declarative Framework for Development of Ergo dApps
Introduction
ErgoScript is the smart contract language used by the Ergo blockchain. While it has concise syntax adopted from Scala/Kotlin, it still may seem confusing at first because conceptually ErgoScript is quite different compared to conventional languages which we all know and love. This is because Ergo is a UTXO based blockchain, whereas smart contracts are traditionally associated with account based systems like Ethereum. However, Ergo's transaction model has many advantages over the account based model and with the right approach it can even be significantly easier to develop Ergo contracts than to write and debug Solidity code.
Below we will cover the key aspects of the Ergo contract model which makes it different:
Paradigm
The account model of Ethereum is imperative. This means that the typical task of sending coins from Alice to Bob requires changing the balances in storage as a series of operations. Ergo's UTXO based programming model on the other hand is declarative. ErgoScript contracts specify conditions for a transaction to be accepted by the blockchain (not changes to be made in the storage state as result of the contract execution).
Scalability
In the account model of Ethereum both storage changes and validity checks are performed on-chain during code execution. In contrast, Ergo transactions are created off-chain and only validation checks are performed on-chain thus reducing the amount of operations performed by every node on the network. In addition, due to immutability of the transaction graph, various optimization strategies are possible to improve throughput of transactions per second in the network. Light verifying nodes are also possible thus further facilitating scalability and accessibility of the network.
Shared state
The account-based model is reliant on shared mutable state which is known to lead to complex semantics (and subtle million dollar bugs) in the context of concurrent/ distributed computation. Ergo's model is based on an immutable graph of transactions. This approach, inherited from Bitcoin, plays well with the concurrent and distributed nature of blockchains and facilitates light trustless clients.
Expressive Power
Ethereum advocated execution of a turing-complete language on the blockchain. It theoretically promised unlimited potential, however in practice severe limitations came to light from excessive blockchain bloat, subtle multi-million dollar bugs, gas costs which limit contract complexity, and other such problems. Ergo on the flip side extends UTXO to enable turing-completeness while limiting the complexity of the ErgoScript language itself. The same expressive power is achieved in a different and more semantically sound way.
With the all of the above points, it should be clear that there are a lot of benefits to the model Ergo is using. In the rest of this article I will introduce you to the concept of FlowCards - a dApp developer component which allows for designing complex Ergo contracts in a declarative and visual way.

From Imperative to Declarative

In the imperative programming model of Ethereum a transaction is a sequence of operations executed by the Ethereum VM. The following Solidity function implements a transfer of tokens from sender to receiver . The transaction starts when sender calls this function on an instance of a contract and ends when the function returns.
// Sends an amount of existing coins from any caller to an address function send(address receiver, uint amount) public { require(amount <= balances[msg.sender], "Insufficient balance."); balances[msg.sender] -= amount; balances[receiver] += amount; emit Sent(msg.sender, receiver, amount); } 
The function first checks the pre-conditions, then updates the storage (i.e. balances) and finally publishes the post-condition as the Sent event. The gas which is consumed by the transaction is sent to the miner as a reward for executing this transaction.
Unlike Ethereum, a transaction in Ergo is a data structure holding a list of input coins which it spends and a list of output coins which it creates preserving the total balances of ERGs and tokens (in which Ergo is similar to Bitcoin).
Turning back to the example above, since Ergo natively supports tokens, therefore for this specific example of sending tokens we don't need to write any code in ErgoScript. Instead we need to create the ‘send’ transaction shown in the following figure, which describes the same token transfer but declaratively.
https://preview.redd.it/sxs3kesvrsv41.png?width=1348&format=png&auto=webp&s=582382bc26912ff79114d831d937d94b6988e69f
The picture visually describes the following steps, which the network user needs to perform:
  1. Select unspent sender's boxes, containing in total tB >= amount of tokens and B >= txFee + minErg ERGs.
  2. Create an output target box which is protected by the receiver public key with minErg ERGs and amount of T tokens.
  3. Create one fee output protected by the minerFee contract with txFee ERGs.
  4. Create one change output protected by the sender public key, containing B - minErg - txFee ERGs and tB - amount of T tokens.
  5. Create a new transaction, sign it using the sender's secret key and send to the Ergo network.
What is important to understand here is that all of these steps are preformed off-chain (for example using Appkit Transaction API) by the user's application. Ergo network nodes don't need to repeat this transaction creation process, they only need to validate the already formed transaction. ErgoScript contracts are stored in the inputs of the transaction and check spending conditions. The node executes the contracts on-chain when the transaction is validated. The transaction is valid if all of the conditions are satisfied.
Thus, in Ethereum when we “send amount from sender to recipient” we are literally editing balances and updating the storage with a concrete set of commands. This happens on-chain and thus a new transaction is also created on-chain as the result of this process.
In Ergo (as in Bitcoin) transactions are created off-chain and the network nodes only verify them. The effects of the transaction on the blockchain state is that input coins (or Boxes in Ergo's parlance) are removed and output boxes are added to the UTXO set.
In the example above we don't use an ErgoScript contract but instead assume a signature check is used as the spending pre-condition. However in more complex application scenarios we of course need to use ErgoScript which is what we are going to discuss next.

From Changing State to Checking Context

In the send function example we first checked the pre-condition (require(amount <= balances[msg.sender],...) ) and then changed the state (i.e. update balances balances[msg.sender] -= amount ). This is typical in Ethereum transactions. Before we change anything we need to check if it is valid to do so.
In Ergo, as we discussed previously, the state (i.e. UTXO set of boxes) is changed implicitly when a valid transaction is included in a block. Thus we only need to check the pre-conditions before the transaction can be added to the block. This is what ErgoScript contracts do.
It is not possible to “change the state” in ErgoScript because it is a language to check pre-conditions for spending coins. ErgoScript is a purely functional language without side effects that operates on immutable data values. This means all the inputs, outputs and other transaction parameters available in a script are immutable. This, among other things, makes ErgoScript a very simple language that is easy to learn and safe to use. Similar to Bitcoin, each input box contains a script, which should return the true value in order to 1) allow spending of the box (i.e. removing from the UTXO set) and 2) adding the transaction to the block.
If we are being pedantic, it is therefore incorrect (strictly speaking) to think of ErgoScript as the language of Ergo contracts, because it is the language of propositions (logical predicates, formulas, etc.) which protect boxes from “illegal” spending. Unlike Bitcoin, in Ergo the whole transaction and a part of the current blockchain context is available to every script. Therefore each script may check which outputs are created by the transaction, their ERG and token amounts (we will use this capability in our example DEX contracts), current block number etc.
In ErgoScript you define the conditions of whether changes (i.e. coin spending) are allowed to happen in a given context. This is in contrast to programming the changes imperatively in the code of a contract.
While Ergo's transaction model unlocks a whole range of applications like (DEX, DeFi Apps, LETS, etc), designing contracts as pre-conditions for coin spending (or guarding scripts) directly is not intuitive. In the next sections we will consider a useful graphical notation to design contracts declaratively using FlowCard Diagrams, which is a visual representation of executable components (FlowCards).
FlowCards aim to radically simplify dApp development on the Ergo platform by providing a high-level declarative language, execution runtime, storage format and a graphical notation.
We will start with a high level of diagrams and go down to FlowCard specification.

FlowCard Diagrams

The idea behind FlowCard diagrams is based on the following observations: 1) An Ergo box is immutable and can only be spent in the transaction which uses it as an input. 2) We therefore can draw a flow of boxes through transactions, so that boxes flowing in to the transaction are spent and those flowing out are created and added to the UTXO. 3) A transaction from this perspective is simply a transformer of old boxes to the new ones preserving the balances of ERGs and tokens involved.
The following figure shows the main elements of the Ergo transaction we've already seen previously (now under the name of FlowCard Diagram).
https://preview.redd.it/06aqkcd1ssv41.png?width=1304&format=png&auto=webp&s=106eda730e0526919aabd5af9596b97e45b69777
There is a strictly defined meaning (semantics) behind every element of the diagram, so that the diagram is a visual representation (or a view) of the underlying executable component (called FlowCard).
The FlowCard can be used as a reusable component of an Ergo dApp to create and initiate the transaction on the Ergo blockchain. We will discuss this in the coming sections.
Now let's look at the individual pieces of the FlowCard diagram one by one.
1. Name and Parameters
Each flow card is given a name and a list of typed parameters. This is similar to a template with parameters. In the above figure we can see the Send flow card which has five parameters. The parameters are used in the specification.
2. Contract Wallet
This is a key element of the flow card. Every box has a guarding script. Often it is the script that checks a signature against a public key. This script is trivial in ErgoScript and is defined like the def pk(pubkey: Address) = { pubkey } template where pubkey is a parameter of the type Address . In the figure, the script template is applied to the parameter pk(sender) and thus a concrete wallet contract is obtained. Therefore pk(sender) and pk(receiver) yield different scripts and represent different wallets on the diagram, even though they use the same template.
Contract Wallet contains a set of all UTXO boxes which have a given script derived from the given script template using flow card parameters. For example, in the figure, the template is pk and parameter pubkey is substituted with the `sender’ flow card parameter.
3. Contract
Even though a contract is a property of a box, on the diagram we group the boxes by their contracts, therefore it looks like the boxes belong to the contracts, rather than the contracts belong to the boxes. In the example, we have three instantiated contracts pk(sender) , pk(receiver) and minerFee . Note, that pk(sender) is the instantiation of the pk template with the concrete parameter sender and minerFee is the instantiation of the pre-defined contract which protects the miner reward boxes.
4. Box name
In the diagram we can give each box a name. Besides readability of the diagram, we also use the name as a synonym of a more complex indexed access to the box in the contract. For example, change is the name of the box, which can also be used in the ErgoScript conditions instead of OUTPUTS(2) . We also use box names to associate spending conditions with the boxes.
5. Boxes in the wallet
In the diagram, we show boxes (darker rectangles) as belonging to the contract wallets (lighter rectangles). Each such box rectangle is connected with a grey transaction rectangle by either orange or green arrows or both. An output box (with an incoming green arrow) may include many lines of text where each line specifies a condition which should be checked as part of the transaction. The first line specifies the condition on the amount of ERG which should be placed in the box. Other lines may take one of the following forms:
  1. amount: TOKEN - the box should contain the given amount of the given TOKEN
  2. R == value - the box should contain the given value of the given register R
  3. boxName ? condition - the box named boxName should check condition in its script.
We discuss these conditions in the sections below.
6. Amount of ERGs in the box
Each box should store a minimum amount of ERGs. This is checked when the creating transaction is validated. In the diagram the amount of ERGs is always shown as the first line (e.g. B: ERG or B - minErg - txFee ). The value type ascription B: ERG is optional and may be used for readability. When the value is given as a formula, then this formula should be respected by the transaction which creates the box.
It is important to understand that variables like amount and txFee are not named properties of the boxes. They are parameters of the whole diagram and representing some amounts. Or put it another way, they are shared parameters between transactions (e.g. Sell Order and Swap transactions from DEX example below share the tAmt parameter). So the same name is tied to the same value throughout the diagram (this is where the tooling would help a lot). However, when it comes to on-chain validation of those values, only explicit conditions which are marked with ? are transformed to ErgoScript. At the same time, all other conditions are ensured off-chain during transaction building (for example in an application using Appkit API) and transaction validation when it is added to the blockchain.
7. Amount of T token
A box can store values of many tokens. The tokens on the diagram are named and a value variable may be associated with the token T using value: T expression. The value may be given by formula. If the formula is prefixed with a box name like boxName ? formula , then it is should also be checked in the guarding script of the boxName box. This additional specification is very convenient because 1) it allows to validate the visual design automatically, and 2) the conditions specified in the boxes of a diagram are enough to synthesize the necessary guarding scripts. (more about this below at “From Diagrams To ErgoScript Contracts”)
8. Tx Inputs
Inputs are connected to the corresponding transaction by orange arrows. An input arrow may have a label of the following forms:
  1. [email protected] - optional name with an index i.e. [email protected] or u/2 . This is a property of the target endpoint of the arrow. The name is used in conditions of related boxes and the index is the position of the corresponding box in the INPUTS collection of the transaction.
  2. !action - is a property of the source of the arrow and gives a name for an alternative spending path of the box (we will see this in DEX example)
Because of alternative spending paths, a box may have many outgoing orange arrows, in which case they should be labeled with different actions.
9. Transaction
A transaction spends input boxes and creates output boxes. The input boxes are given by the orange arrows and the labels are expected to put inputs at the right indexes in INPUTS collection. The output boxes are given by the green arrows. Each transaction should preserve a strict balance of ERG values (sum of inputs == sum of outputs) and for each token the sum of inputs >= the sum of outputs. The design diagram requires an explicit specification of the ERG and token values for all of the output boxes to avoid implicit errors and ensure better readability.
10. Tx Outputs
Outputs are connected to the corresponding transaction by green arrows. An output arrow may have a label of the following [email protected] , where an optional name is accompanied with an index i.e. [email protected] or u/2 . This is a property of the source endpoint of the arrow. The name is used in conditions of the related boxes and the index is the position of the corresponding box in the OUTPUTS collection of the transaction.

Example: Decentralized Exchange (DEX)

Now let's use the above described notation to design a FlowCard for a DEX dApp. It is simple enough yet also illustrates all of the key features of FlowCard diagrams which we've introduced in the previous section.
The dApp scenario is shown in the figure below: There are three participants (buyer, seller and DEX) of the DEX dApp and five different transaction types, which are created by participants. The buyer wants to swap ergAmt of ERGs for tAmt of TID tokens (or vice versa, the seller wants to sell TID tokens for ERGs, who sends the order first doesn't matter). Both the buyer and the seller can cancel their orders any time. The DEX off-chain matching service can find matching orders and create the Swap transaction to complete the exchange.
The following diagram fully (and formally) specifies all of the five transactions that must be created off-chain by the DEX dApp. It also specifies all of the spending conditions that should be verified on-chain.

https://preview.redd.it/piogz0v9ssv41.png?width=1614&format=png&auto=webp&s=e1b503a635ad3d138ef91e2f0c3b726e78958646
Let's discuss the FlowCard diagram and the logic of each transaction in details:
Buy Order Transaction
A buyer creates a Buy Order transaction. The transaction spends E amount of ERGs (which we will write E: ERG ) from one or more boxes in the pk(buyer) wallet. The transaction creates a bid box with ergAmt: ERG protected by the buyOrder script. The buyOrder script is synthesized from the specification (see below at “From Diagrams To ErgoScript Contracts”) either manually or automatically by a tool. Even though we don't need to define the buyOrder script explicitly during designing, at run time the bid box should contain the buyOrder script as the guarding proposition (which checks the box spending conditions), otherwise the conditions specified in the diagram will not be checked.
The change box is created to make the input and output sums of the transaction balanced. The transaction fee box is omitted because it can be added automatically by the tools. In practice, however, the designer can add the fee box explicitly to the a diagram. It covers the cases of more complex transactions (like Swap) where there are many ways to pay the transaction fee.
Cancel Buy, Cancel Sell Transactions
At any time, the buyer can cancel the order by sending CancelBuy transaction. The transaction should satisfy the guarding buyOrder contract which protects the bid box. As you can see on the diagram, both the Cancel and the Swap transactions can spend the bid box. When a box has spending alternatives (or spending paths) then each alternative is identified by a unique name prefixed with ! (!cancel and !swap for the bid box). Each alternative path has specific spending conditions. In our example, when the Cancel Buy transaction spends the bid box the ?buyer condition should be satisfied, which we read as “the signature for the buyer address should be presented in the transaction”. Therefore, only buyer can cancel the buy order. This “signature” condition is only required for the !cancel alternative spending path and not required for !swap .
Sell Order Transaction
The Sell Order transaction is similar to the BuyOrder in that it deals with tokens in addition to ERGs. The transaction spends E: ERG and T: TID tokens from seller's wallet (specified as pk(seller) contract). The two outputs are ask and change . The change is a standard box to balance transaction. The ask box keeps tAmt: TID tokens for the exchange and minErg: ERG - the minimum amount of ERGs required in every box.
Swap Transaction
This is a key transaction in the DEX dApp scenario. The transaction has several spending conditions on the input boxes and those conditions are included in the buyOrder and sellOrder scripts (which are verified when the transaction is added to the blockchain). However, on the diagram those conditions are not specified in the bid and ask boxes, they are instead defined in the output boxes of the transaction.
This is a convention for improved usability because most of the conditions relate to the properties of the output boxes. We could specify those properties in the bid box, but then we would have to use more complex expressions.
Let's consider the output created by the arrow labeled with [email protected] . This label tells us that the output is at the index 0 in the OUTPUTS collection of the transaction and that in the diagram we can refer to this box by the buyerOut name. Thus we can label both the box itself and the arrow to give the box a name.
The conditions shown in the buyerOut box have the form bid ? condition , which means they should be verified on-chain in order to spend the bid box. The conditions have the following meaning:
  • tAmt: TID requires the box to have tAmt amount of TID token
  • R4 == bid.id requires R4 register in the box to be equal to id of the bid box.
  • script == buyer requires the buyerOut box to have the script of the wallet where it is located on the diagram, i.e. pk(buyer)
Similar properties are added to the sellerOut box, which is specified to be at index 1 and the name is given to it using the label on the box itself, rather than on the arrow.
The Swap transaction spends two boxes bid and ask using the !swap spending path on both, however unlike !cancel the conditions on the path are not specified. This is where the bid ? and ask ? prefixes come into play. They are used so that the conditions listed in the buyerOut and sellerOut boxes are moved to the !swap spending path of the bid and ask boxes correspondingly.
If you look at the conditions of the output boxes, you will see that they exactly specify the swap of values between seller's and buyer's wallets. The buyer gets the necessary amount of TID token and seller gets the corresponding amount of ERGs. The Swap transaction is created when there are two matching boxes with buyOrder and sellOrder contracts.

From Diagrams To ErgoScript Contracts

What is interesting about FlowCard specifications is that we can use them to automatically generate the necessary ErgoTree scripts. With the appropriate tooling support this can be done automatically, but with the lack of thereof, it can be done manually. Thus, the FlowCard allows us to capture and visually represent all of the design choices and semantic details of an Ergo dApp.
What we are going to do next is to mechanically create the buyOrder contract from the information given in the DEX flow card.
Recall that each script is a proposition (boolean valued expression) which should evaluate to true to allow spending of the box. When we have many conditions to be met at the same time we can combine them in a logical formula using the AND binary operation, and if we have alternatives (not necessarily exclusive) we can put them into the OR operation.
The buyOrder box has the alternative spending paths !cancel and !swap . Thus the ErgoScript code should have OR operation with two arguments - one for each spending path.
/** buyOrder contract */ { val cancelCondition = {} val swapCondition = {} cancelCondition || swapCondition } 
The formula for the cancelCondition expression is given in the !cancel spending path of the buyOrder box. We can directly include it in the script.
/** buyOrder contract */ { val cancelCondition = { buyer } val swapCondition = {} cancelCondition || swapCondition } 
For the !swap spending path of the buyOrder box the conditions are specified in the buyerOut output box of the Swap transaction. If we simply include them in the swapCondition then we get a syntactically incorrect script.
/** buyOrder contract */ { val cancelCondition = { buyer } val swapCondition = { tAmt: TID && R4 == bid.id && @contract } cancelCondition || swapCondition } 
We can however translate the conditions from the diagram syntax to ErgoScript expressions using the following simple rules
  1. [email protected] ==> val buyerOut = OUTPUTS(0)
  2. tAmt: TID ==> tid._2 == tAmt where tid = buyerOut.tokens(TID)
  3. R4 == bid.id ==> R4 == SELF.id where R4 = buyerOut.R4[Coll[Byte]].get
  4. script == buyer ==> buyerOut.propositionBytes == buyer.propBytes
Note, in the diagram TID represents a token id, but ErgoScript doesn't have access to the tokens by the ids so we cannot write tokens.getByKey(TID) . For this reason, when the diagram is translated into ErgoScript, TID becomes a named constant of the index in tokens collection of the box. The concrete value of the constant is assigned when the BuyOrder transaction with the buyOrder box is created. The correspondence and consistency between the actual tokenId, the TID constant and the actual tokens of the buyerOut box is ensured by the off-chain application code, which is completely possible since all of the transactions are created by the application using FlowCard as a guiding specification. This may sound too complicated, but this is part of the translation from diagram specification to actual executable application code, most of which can be automated.
After the transformation we can obtain a correct script which checks all the required preconditions for spending the buyOrder box.
/** buyOrder contract */ def DEX(buyer: Addrss, seller: Address, TID: Int, ergAmt: Long, tAmt: Long) { val cancelCondition: SigmaProp = { buyer } // verify buyer's sig (ProveDlog) val swapCondition = OUTPUTS.size > 0 && { // securing OUTPUTS access val buyerOut = OUTPUTS(0) // from [email protected] buyerOut.tokens.size > TID && { // securing tokens access val tid = buyerOut.tokens(TID) val regR4 = buyerOut.R4[Coll[Byte]] regR4.isDefined && { // securing R4 access val R4 = regR4.get tid._2 == tAmt && // from tAmt: TID R4 == SELF.id && // from R4 == bid.id buyerOut.propositionBytes == buyer.propBytes // from script == buyer } } } cancelCondition || swapCondition } 
A similar script for the sellOrder box can be obtained using the same translation rules. With the help of the tooling the code of contracts can be mechanically generated from the diagram specification.

Conclusions

Declarative programming models have already won the battle against imperative programming in many application domains like Big Data, Stream Processing, Deep Learning, Databases, etc. Ergo is pioneering the declarative model of dApp development as a better and safer alternative to the now popular imperative model of smart contracts.
The concept of FlowCard shifts the focus from writing ErgoScript contracts to the overall flow of values (hence the name), in such a way, that ErgoScript can always be generated from them. You will never need to look at the ErgoScript code once the tooling is in place.
Here are the possible next steps for future work:
  1. Storage format for FlowCard Spec and the corresponding EIP standardized file format (Json/XML/Protobuf). This will allow various tools (Diagram Editor, Runtime, dApps etc) to create and use *.flowcard files.
  2. FlowCard Viewer, which can generate the diagrams from *.flowcard files.
  3. FlowCard Runtime, which can run *.flowcard files, create and send transactions to Ergo network.
  4. FlowCard Designer Tool, which can simplify development of complex diagrams . This will make designing and validation of Ergo contracts a pleasant experience, more like drawing rather than coding. In addition, the correctness of the whole dApp scenario can be verified and controlled by the tooling.
submitted by eleanorcwhite to btc [link] [comments]

Technical: A Brief History of Payment Channels: from Satoshi to Lightning Network

Who cares about political tweets from some random country's president when payment channels are a much more interesting and are actually capable of carrying value?
So let's have a short history of various payment channel techs!

Generation 0: Satoshi's Broken nSequence Channels

Because Satoshi's Vision included payment channels, except his implementation sucked so hard we had to go fix it and added RBF as a by-product.
Originally, the plan for nSequence was that mempools would replace any transaction spending certain inputs with another transaction spending the same inputs, but only if the nSequence field of the replacement was larger.
Since 0xFFFFFFFF was the highest value that nSequence could get, this would mark a transaction as "final" and not replaceable on the mempool anymore.
In fact, this "nSequence channel" I will describe is the reason why we have this weird rule about nLockTime and nSequence. nLockTime actually only works if nSequence is not 0xFFFFFFFF i.e. final. If nSequence is 0xFFFFFFFF then nLockTime is ignored, because this if the "final" version of the transaction.
So what you'd do would be something like this:
  1. You go to a bar and promise the bartender to pay by the time the bar closes. Because this is the Bitcoin universe, time is measured in blockheight, so the closing time of the bar is indicated as some future blockheight.
  2. For your first drink, you'd make a transaction paying to the bartender for that drink, paying from some coins you have. The transaction has an nLockTime equal to the closing time of the bar, and a starting nSequence of 0. You hand over the transaction and the bartender hands you your drink.
  3. For your succeeding drink, you'd remake the same transaction, adding the payment for that drink to the transaction output that goes to the bartender (so that output keeps getting larger, by the amount of payment), and having an nSequence that is one higher than the previous one.
  4. Eventually you have to stop drinking. It comes down to one of two possibilities:
    • You drink until the bar closes. Since it is now the nLockTime indicated in the transaction, the bartender is able to broadcast the latest transaction and tells the bouncers to kick you out of the bar.
    • You wisely consider the state of your liver. So you re-sign the last transaction with a "final" nSequence of 0xFFFFFFFF i.e. the maximum possible value it can have. This allows the bartender to get his or her funds immediately (nLockTime is ignored if nSequence is 0xFFFFFFFF), so he or she tells the bouncers to let you out of the bar.
Now that of course is a payment channel. Individual payments (purchases of alcohol, so I guess buying coffee is not in scope for payment channels). Closing is done by creating a "final" transaction that is the sum of the individual payments. Sure there's no routing and channels are unidirectional and channels have a maximum lifetime but give Satoshi a break, he was also busy inventing Bitcoin at the time.
Now if you noticed I called this kind of payment channel "broken". This is because the mempool rules are not consensus rules, and cannot be validated (nothing about the mempool can be validated onchain: I sigh every time somebody proposes "let's make block size dependent on mempool size", mempool state cannot be validated by onchain data). Fullnodes can't see all of the transactions you signed, and then validate that the final one with the maximum nSequence is the one that actually is used onchain. So you can do the below:
  1. Become friends with Jihan Wu, because he owns >51% of the mining hashrate (he totally reorged Bitcoin to reverse the Binance hack right?).
  2. Slip Jihan Wu some of the more interesting drinks you're ordering as an incentive to cooperate with you. So say you end up ordering 100 drinks, you split it with Jihan Wu and give him 50 of the drinks.
  3. When the bar closes, Jihan Wu quickly calls his mining rig and tells them to mine the version of your transaction with nSequence 0. You know, that first one where you pay for only one drink.
  4. Because fullnodes cannot validate nSequence, they'll accept even the nSequence=0 version and confirm it, immutably adding you paying for a single alcoholic drink to the blockchain.
  5. The bartender, pissed at being cheated, takes out a shotgun from under the bar and shoots at you and Jihan Wu.
  6. Jihan Wu uses his mystical chi powers (actually the combined exhaust from all of his mining rigs) to slow down the shotgun pellets, making them hit you as softly as petals drifting in the wind.
  7. The bartender mutters some words, clothes ripping apart as he or she (hard to believe it could be a she but hey) turns into a bear, ready to maul you for cheating him or her of the payment for all the 100 drinks you ordered from him or her.
  8. Steely-eyed, you stand in front of the bartender-turned-bear, daring him to touch you. You've watched Revenant, you know Leonardo di Caprio could survive a bear mauling, and if some posh actor can survive that, you know you can too. You make a pose. "Drunken troll logic attack!"
  9. I think I got sidetracked here.
Lessons learned?

Spilman Channels

Incentive-compatible time-limited unidirectional channel; or, Satoshi's Vision, Fixed (if transaction malleability hadn't been a problem, that is).
Now, we know the bartender will turn into a bear and maul you if you try to cheat the payment channel, and now that we've revealed you're good friends with Jihan Wu, the bartender will no longer accept a payment channel scheme that lets one you cooperate with a miner to cheat the bartender.
Fortunately, Jeremy Spilman proposed a better way that would not let you cheat the bartender.
First, you and the bartender perform this ritual:
  1. You get some funds and create a transaction that pays to a 2-of-2 multisig between you and the bartender. You don't broadcast this yet: you just sign it and get its txid.
  2. You create another transaction that spends the above transaction. This transaction (the "backoff") has an nLockTime equal to the closing time of the bar, plus one block. You sign it and give this backoff transaction (but not the above transaction) to the bartender.
  3. The bartender signs the backoff and gives it back to you. It is now valid since it's spending a 2-of-2 of you and the bartender, and both of you have signed the backoff transaction.
  4. Now you broadcast the first transaction onchain. You and the bartender wait for it to be deeply confirmed, then you can start ordering.
The above is probably vaguely familiar to LN users. It's the funding process of payment channels! The first transaction, the one that pays to a 2-of-2 multisig, is the funding transaction that backs the payment channel funds.
So now you start ordering in this way:
  1. For your first drink, you create a transaction spending the funding transaction output and sending the price of the drink to the bartender, with the rest returning to you.
  2. You sign the transaction and pass it to the bartender, who serves your first drink.
  3. For your succeeding drinks, you recreate the same transaction, adding the price of the new drink to the sum that goes to the bartender and reducing the money returned to you. You sign the transaction and give it to the bartender, who serves you your next drink.
  4. At the end:
    • If the bar closing time is reached, the bartender signs the latest transaction, completing the needed 2-of-2 signatures and broadcasting this to the Bitcoin network. Since the backoff transaction is the closing time + 1, it can't get used at closing time.
    • If you decide you want to leave early because your liver is crying, you just tell the bartender to go ahead and close the channel (which the bartender can do at any time by just signing and broadcasting the latest transaction: the bartender won't do that because he or she is hoping you'll stay and drink more).
    • If you ended up just hanging around the bar and never ordering, then at closing time + 1 you broadcast the backoff transaction and get your funds back in full.
Now, even if you pass 50 drinks to Jihan Wu, you can't give him the first transaction (the one which pays for only one drink) and ask him to mine it: it's spending a 2-of-2 and the copy you have only contains your own signature. You need the bartender's signature to make it valid, but he or she sure as hell isn't going to cooperate in something that would lose him or her money, so a signature from the bartender validating old state where he or she gets paid less isn't going to happen.
So, problem solved, right? Right? Okay, let's try it. So you get your funds, put them in a funding tx, get the backoff tx, confirm the funding tx...
Once the funding transaction confirms deeply, the bartender laughs uproariously. He or she summons the bouncers, who surround you menacingly.
"I'm refusing service to you," the bartender says.
"Fine," you say. "I was leaving anyway;" You smirk. "I'll get back my money with the backoff transaction, and posting about your poor service on reddit so you get negative karma, so there!"
"Not so fast," the bartender says. His or her voice chills your bones. It looks like your exploitation of the Satoshi nSequence payment channel is still fresh in his or her mind. "Look at the txid of the funding transaction that got confirmed."
"What about it?" you ask nonchalantly, as you flip open your desktop computer and open a reputable blockchain explorer.
What you see shocks you.
"What the --- the txid is different! You--- you changed my signature?? But how? I put the only copy of my private key in a sealed envelope in a cast-iron box inside a safe buried in the Gobi desert protected by a clan of nomads who have dedicated their lives and their childrens' lives to keeping my private key safe in perpetuity!"
"Didn't you know?" the bartender asks. "The components of the signature are just very large numbers. The sign of one of the signature components can be changed, from positive to negative, or negative to positive, and the signature will remain valid. Anyone can do that, even if they don't know the private key. But because Bitcoin includes the signatures in the transaction when it's generating the txid, this little change also changes the txid." He or she chuckles. "They say they'll fix it by separating the signatures from the transaction body. They're saying that these kinds of signature malleability won't affect transaction ids anymore after they do this, but I bet I can get my good friend Jihan Wu to delay this 'SepSig' plan for a good while yet. Friendly guy, this Jihan Wu, it turns out all I had to do was slip him 51 drinks and he was willing to mine a tx with the signature signs flipped." His or her grin widens. "I'm afraid your backoff transaction won't work anymore, since it spends a txid that is not existent and will never be confirmed. So here's the deal. You pay me 99% of the funds in the funding transaction, in exchange for me signing the transaction that spends with the txid that you see onchain. Refuse, and you lose 100% of the funds and every other HODLer, including me, benefits from the reduction in coin supply. Accept, and you get to keep 1%. I lose nothing if you refuse, so I won't care if you do, but consider the difference of getting zilch vs. getting 1% of your funds." His or her eyes glow. "GENUFLECT RIGHT NOW."
Lesson learned?

CLTV-protected Spilman Channels

Using CLTV for the backoff branch.
This variation is simply Spilman channels, but with the backoff transaction replaced with a backoff branch in the SCRIPT you pay to. It only became possible after OP_CHECKLOCKTIMEVERIFY (CLTV) was enabled in 2015.
Now as we saw in the Spilman Channels discussion, transaction malleability means that any pre-signed offchain transaction can easily be invalidated by flipping the sign of the signature of the funding transaction while the funding transaction is not yet confirmed.
This can be avoided by simply putting any special requirements into an explicit branch of the Bitcoin SCRIPT. Now, the backoff branch is supposed to create a maximum lifetime for the payment channel, and prior to the introduction of OP_CHECKLOCKTIMEVERIFY this could only be done by having a pre-signed nLockTime transaction.
With CLTV, however, we can now make the branches explicit in the SCRIPT that the funding transaction pays to.
Instead of paying to a 2-of-2 in order to set up the funding transaction, you pay to a SCRIPT which is basically "2-of-2, OR this singlesig after a specified lock time".
With this, there is no backoff transaction that is pre-signed and which refers to a specific txid. Instead, you can create the backoff transaction later, using whatever txid the funding transaction ends up being confirmed under. Since the funding transaction is immutable once confirmed, it is no longer possible to change the txid afterwards.

Todd Micropayment Networks

The old hub-spoke model (that isn't how LN today actually works).
One of the more direct predecessors of the Lightning Network was the hub-spoke model discussed by Peter Todd. In this model, instead of payers directly having channels to payees, payers and payees connect to a central hub server. This allows any payer to pay any payee, using the same channel for every payee on the hub. Similarly, this allows any payee to receive from any payer, using the same channel.
Remember from the above Spilman example? When you open a channel to the bartender, you have to wait around for the funding tx to confirm. This will take an hour at best. Now consider that you have to make channels for everyone you want to pay to. That's not very scalable.
So the Todd hub-spoke model has a central "clearing house" that transport money from payers to payees. The "Moonbeam" project takes this model. Of course, this reveals to the hub who the payer and payee are, and thus the hub can potentially censor transactions. Generally, though, it was considered that a hub would more efficiently censor by just not maintaining a channel with the payer or payee that it wants to censor (since the money it owned in the channel would just be locked uselessly if the hub won't process payments to/from the censored user).
In any case, the ability of the central hub to monitor payments means that it can surveill the payer and payee, and then sell this private transactional data to third parties. This loss of privacy would be intolerable today.
Peter Todd also proposed that there might be multiple hubs that could transport funds to each other on behalf of their users, providing somewhat better privacy.
Another point of note is that at the time such networks were proposed, only unidirectional (Spilman) channels were available. Thus, while one could be a payer, or payee, you would have to use separate channels for your income versus for your spending. Worse, if you wanted to transfer money from your income channel to your spending channel, you had to close both and reshuffle the money between them, both onchain activities.

Poon-Dryja Lightning Network

Bidirectional two-participant channels.
The Poon-Dryja channel mechanism has two important properties:
Both the original Satoshi and the two Spilman variants are unidirectional: there is a payer and a payee, and if the payee wants to do a refund, or wants to pay for a different service or product the payer is providing, then they can't use the same unidirectional channel.
The Poon-Dryjam mechanism allows channels, however, to be bidirectional instead: you are not a payer or a payee on the channel, you can receive or send at any time as long as both you and the channel counterparty are online.
Further, unlike either of the Spilman variants, there is no time limit for the lifetime of a channel. Instead, you can keep the channel open for as long as you want.
Both properties, together, form a very powerful scaling property that I believe most people have not appreciated. With unidirectional channels, as mentioned before, if you both earn and spend over the same network of payment channels, you would have separate channels for earning and spending. You would then need to perform onchain operations to "reverse" the directions of your channels periodically. Secondly, since Spilman channels have a fixed lifetime, even if you never used either channel, you would have to periodically "refresh" it by closing it and reopening.
With bidirectional, indefinite-lifetime channels, you may instead open some channels when you first begin managing your own money, then close them only after your lawyers have executed your last will and testament on how the money in your channels get divided up to your heirs: that's just two onchain transactions in your entire lifetime. That is the potentially very powerful scaling property that bidirectional, indefinite-lifetime channels allow.
I won't discuss the transaction structure needed for Poon-Dryja bidirectional channels --- it's complicated and you can easily get explanations with cute graphics elsewhere.
There is a weakness of Poon-Dryja that people tend to gloss over (because it was fixed very well by RustyReddit):
Another thing I want to emphasize is that while the Lightning Network paper and many of the earlier presentations developed from the old Peter Todd hub-and-spoke model, the modern Lightning Network takes the logical conclusion of removing a strict separation between "hubs" and "spokes". Any node on the Lightning Network can very well work as a hub for any other node. Thus, while you might operate as "mostly a payer", "mostly a forwarding node", "mostly a payee", you still end up being at least partially a forwarding node ("hub") on the network, at least part of the time. This greatly reduces the problems of privacy inherent in having only a few hub nodes: forwarding nodes cannot get significantly useful data from the payments passing through them, because the distance between the payer and the payee can be so large that it would be likely that the ultimate payer and the ultimate payee could be anyone on the Lightning Network.
Lessons learned?

Future

After LN, there's also the Decker-Wattenhofer Duplex Micropayment Channels (DMC). This post is long enough as-is, LOL. But for now, it uses a novel "decrementing nSequence channel", using the new relative-timelock semantics of nSequence (not the broken one originally by Satoshi). It actually uses multiple such "decrementing nSequence" constructs, terminating in a pair of Spilman channels, one in both directions (thus "duplex"). Maybe I'll discuss it some other time.
The realization that channel constructions could actually hold more channel constructions inside them (the way the Decker-Wattenhofer puts a pair of Spilman channels inside a series of "decrementing nSequence channels") lead to the further thought behind Burchert-Decker-Wattenhofer channel factories. Basically, you could host multiple two-participant channel constructs inside a larger multiparticipant "channel" construct (i.e. host multiple channels inside a factory).
Further, we have the Decker-Russell-Osuntokun or "eltoo" construction. I'd argue that this is "nSequence done right". I'll write more about this later, because this post is long enough.
Lessons learned?
submitted by almkglor to Bitcoin [link] [comments]

My Ethereum Prediction From 2017. Still Think I was Wrong?

Link to the original post is at the bottom.

Ethereum made one mistake, talking about its future contributions before people could fully perceive them. for anyone that believes ethereum is undervalued it is my opinion you cannot comprehend abstract ideas or conceptualize what ehtereum and blockchain technology actually is.
cryptocurrencies as a digital asset are cool, fun to play with and not typically a bad investment as they are based off the value of bitcoin.
bitcoin as a form of currency has its place and will more than likely ( by means of Litecoin ) aquire a 50 billion dollar market share of cross border money transfer services current rates require 10%+ of the sent value. litecoin does this for about 1%-10% of that. (0.01%-1% and in actuality less in most cases ) divide 84 million coins (max available at production end) by 500 billion (yearly cross border money transfers) roughly $4500 per coin is the minimum value of each coin to cover just one year of money transfers. rest assured it will be higher.
ethereum is efficiency , it is balance, equality, cooperation, innovation, security, and accountability. Ethereum is progress in the name of the greater good of all mankind not just the elite. Ethereum is a social Democracy
all of this sounds nice .... which is what Ethereum promises. people need proof before investing. and that is why you will be just a moment to late. because once it's a sure thing everyone will be investing.
blockchain technology is the real use of digital assets. imagine the following, all media content can be easily published on the blockchain providing two advantages, instant alert to its previous creation if applicable (through the entire database being accessible for instant search and comparison of all published media ) instant encryption ensuring piracy is lessened ( future application software will not be downloadable its code will exist in the ethereum "cloud based" network) the media can be viewed, shared, or done with as is desired, but only to the limits permitted by its creator and only when accessed through a supported ethereum network affiliate using ethereums "Token" to powe rthe software allowing the creator of the content to share their creation. furthermore the creator is capable of issuing their own proprietary tokens that allow them to essentially grant access to their creation to anyone in posession of their "token"
The reason that you cannot comprehend Ethereum is the same reason your parents dont understand bitcoin, why your grandma will never comprehend the internet, why her mother doubted electricity, and her mother didnt see how coal could move a 50 ton train. that reason ? you are all just one generation behind in respect to grasping the concept, for which you have nothing to base its technology off of Ethereum is the next step in innovation. we all wondered what form the next leap in progress would take every great leap in technology is not recognized immediately but when initiated they cannot be stopped. the chain cannot be stopped it just moves forward. building on every advancement that comes before it.
whatare these apps ?.....
medical information will be on ethereum network.... the entire medical database of the world will be connected. acting as a living network updated instantaneously patients symptoms will have quantifiable values, vital statistics will be available for every patient that has ever had the symptoms that any given patient comes in with. by inputting the data of a patient the network uses event related probability to calculate a given set of all possible cases where the data matched with other patients ( millions of variables are considered in an instant.) to diagnose and treat patients according to the most succesful course of action as time goes on after years of trial and error the data will eventually reach a near 100% success rate. faster than we ever thought possible.
Television. cable will end see my remaining thoughts down below for why. netflix style content will replace it. tokens will be distributed. by movie producers meaning a handful of affiliates have access to the rights to distribute them. and netflix will require you to buy its token to have access.
pandora style radio tokens
gps tokens,
but why ?
by making specific tokens account for specific services we can prevent inflation. we also give a value to our money supply. remember when we had money backed by gold ? a dollar could be exchanged for its value in gold. well thats your answer. we have returned to a barter system where i can trade my own services for your services or a future promise that you can at any time redeem said token for my service, or trade for other services. ultimately our money can be thought of as bitcoin and the gold is all other coins. fiat or at least a hard money currency will always exist although two things will occur because of that. people will not be as likely to keep large amounts of money outside of the system as it will depreciate. in most cases over long periods of time. take 10 dollars out for a year and when you come back to buy the equivelent in bitcoin you will likely receive less than if it stayd in the system. where as hard currency versions of bitcoin will retain their value. that theory should hold until 2041 when all coins have been mined and by that time i would bet everyone has jumpedon board. and global currencies will have traded in their fiatmoney to make huge gains from the appreciation of bitcoin integration. i believe bitcoin will be more than an investment it is a replacement as well as a return to the gold standard.
if my outlook holds true then wewill all get an identity token. with that token you can vote on everything from what to spend the pto funds on to what roads need to be built in your city to whether that 150 million dollars should go towards researching the effects of mustard gas on purple monkeys or if it might be better served providing 2 and a half million children with water that hasnt been filled with biological waste. or maybe to give power to 20 million human beings that have lived their entire life without it.
we will have a global currency (bitcoin) and all goods and services will add to its overall marketcap. one services sucess adds to the value of all services. if you do roofing in the the summer your toens will be more valuable. if people cant afford your service then they can contribute to the mining of that service if you allow it. if yoou want to support a cause like funding research on autism then you can go and buy their coin. their service is to find a cure and if its important to people then they will continue to do so. if it is meaningless we as a society will not buy their coin and they will have to find a new job, or keep it as a hobby. either way its not up to a group of people that find it unnecessary it is the decision of the entire world as a collective entity.
many will read what i am about to say and it will cause everything i have said to be no longer looked at as credible. for this i am sorry that you are unable to think of anyone in this world but yourself, and it is people like you that have brought us to this point. socialism always failed in the worlds eyes as did communism. on paper the greatest civilization and its structure are ones in which people work together and do not worry about accumulating wealth in order to live in excess. the wealth is distributed equally, some positions which are harder to fill or require more skills will in the end offer higher pay for their tokens but only because there will be a supply and demand effect created due to its nature of less people being capable of supplying that service/good. on the flip side i believe that by the same token certain positions will ultimately demand a far higher pay. do you want to clean shit out of a porta potty ? probably not so when you need someone else to do it guess what you are going to pay that guy/girl exactly what it costs to have someone do it or you can do it yourself either way supply and demand dictates the value and the most agreed upon value between the provider and the consumer will prevail.




Card

submitted by buybitcoinsites_com to u/buybitcoinsites_com [link] [comments]

XAYA: State Channels for Blockchain Gaming Universes

Hey all, I'd like to turn everyone's attention to a phenomenal ICO that is nearing completion and has ran under the radar for far too long.
XAYA is the first generation 3 blockchain geared towards blockchain gaming, and the only initiative in the niche with a proper solution to the cost, speed, and scalability issues that currently plague blockchain game.
Key Factors:
Token Economics:
Why gamers will use XAYA:
Why developers will use XAYA:
Lastly, a small batch of CHI is currently available on Liquid at a 15% discount as "Phase 1" of the crowdsale. This is the last time to buy CHI at a discount and there are only a couple hundred thousand $$ worth of CHI at this price.
If you have any questions about the project I'm happy to answer.
DISCLAIMER: I am an old Huntercoin player and long-time supporter of the project.
submitted by jeffthedunker to CryptoMoonShots [link] [comments]

Blockchain to fix horribly broken e-mail system like it is today?

E-mail as it is, is horribly broken. Horrendously broken.
It wasn't that many years ago that you could be assured your e-mail reaches whoever you were mailing to. Today it is a mere suggestion, that perhaps this should be delivered to this person, at least for any automated e-mail. This seems to be creeping to manual, organic email as well. Hell, we are seeing even internal e-mails being flagged by spamassassin as spam, organic, human written conversations! In that instance, the spamassassin is also maintained by one of the largest hosting providers in the world...
Hotmail/MS services has been for years (atleast about 4 years now!) been silently dropping email, not all, but some. There's a bit of relief lately, as they have started to favor a bit more marking as spam, rather than silently dropping.
I know, most email users don't see this problem, but those who use email a lot to do their work, and those who need to send automated emails (say, welcome e-mails for a service) this is a big problem. (Disclaimer, for us, our niche of hosting probably causes flagging as well. Our site is blocked by many corporate firewalls for example)
Blockchain to the rescue?
This is an idea i've been toying around with a few years. What if any single e-mail would cost a faction of a cent, and who receives the e-mail, gets paid for it? Now that would solve a lot of problems. I realize there has been some half assed attempts on blockchain based e-mail, but they are about replacing email (never going to happen). Using blockchain to enhance the current experience, with least minimal friction should be the goal, not re-inventing the wheel.
Imagine a say 0.01 cent (0.0001 USD) cost per e-mail. This price would not be cost prohibitive even for free e-mail service providers (Ad revenue etc. should exceed this value), never mind any legit e-mail users. Especially considering you get paid for receiving. So all legit e-mail services would work rather well regardless of the cost. (never mind free email service could profit from this)
Spam however? To send 1 million emails you would need to pay 100$. How many spammers would continue doing so? At least it makes things much harder, not so easy to use a botnet to send your email when you need to include your private key(s) to the botnet, or make some kind of private key management system, makes more complicated.
Small business newsletters? Say you need to send 100k e-mails to legit customers, 10$ is nothing. To human time crafting that newsletter is order (possibly orders) of magnitude greater than that.
Price would also fluctuate as per the market. The most difficult thing would probably be setting the self balancing mechanisms to keep per mail cost sensible. As such, the biggest hurdle in this might not be technical at all.
Technically, how could this work?
Sender sends a TX for e-mail they are sending for recipient. This TX contains message with mail ID, and a segment which can be used with the email contents to unlock the private key for the payment. This way it is verified that recipient mail servers receives and reads the email. Once the recipient server has calculated the private key, they can either TX the received sum to their wallet, or this needs to be formatted so that once the sender has sent it, they cannot recover the private key and double spend (technical hurdle A. For someone who knows their stuff unlikely to be an major hurdle)
Step by step repeat: * Sender checks if recipient has "MailCoin" capability * Sender sends TX to recipient * Sender sends the email to recipient * Recipient notices on mail header (say x-mailcoin-tx: TXID_HERE) that this is a "mailcoin" mail * Recipient checks TX if it has been received * Recipient puts the mail on delivery queue, antispam is instructed of heavy negative score (MTA admin configurable) * Recipient claims the value of the TX (this is the hurdle A). Recipient can only claim the TX value in case they have received the full e-mail. (Question, can this step be pushed even further down the delivery chain, but still remain MTA only level without mail client support?). Most likely solution is that the header contains the encrypted private key, and chain TX contains the key to decrypt that private key to claim the coins, or vice-versa?
Once recipient has the email & payment, they simply mark on their Antispam a automatic lower score and deliver it normally.
E-mail server side we have several components:
Most typical scenario would be the Recipient server works as outgoing as well, with single wallet. So depending on your mail volume, do you send or receive more on that wallet you might never need to worry about the coins (except for value going skyhigh and having like 10k $ worth of "MailCoins").
So perhaps additional components on per use case are needed, or more likely rudimentary scripting capability (ie. "MailCoin" daemon api) to keep the balances in check.
Technical hurdle B: This needs to be super super simple to setup. Or sufficient financial incentive. One would need to develop standard components & configs for exim, postfix, and other MTAs. Infact, make it autogenerate wallet ID etc. and easy to replace or import private keys etc. to put in coins for sending if you need to.
Privacy: On the blockchain you would not see the e-mail contents, only that e-mail likely took place (TX with mail UUID) to recipient. If sender can be deciphered it depends on them if it can be traced who they were. Automatic mixers? :) Recipient can also keep cycling the receive addresses to keep things private if they want to.
The biggest problem i see here, is that if an attacker can deduce the sender and/or recipient, it might to lead to some issues out of the scope of technical solutions. If attacker could read the emails, they would already have accomplished MitM and could just grab all e-mails.
Default implementation should be so, that from recipient address outsider cannot deduce the recipient server nor hostname.
Also, if attacker gains access to your mail with full headers, they could see the TXs in blockchain. MTA might need to scrub mailcoin related headers (yuck, scrubbing headers ....) for paranoid users, but most likely solution is that recipient retransmits those mailcoins as soon as they got the private key for the balance.
Blockchain: Blocks needs to be done every 10seconds or so, it needs to be fast. Preferrably even every 5 seconds, as not to cause any undue delay. Then again, if your application is reliant on receiving email within seconds, one should consider another means for communicating. Imho, email should be considered a little bit like snail mail, but on internet pace: Couple minutes delay is just OK.
Block size given the e-mail volume needs to be fairly large as well, considering the time between blocks. This is technical hurdle C: Hosting the full blockchain. I can easily foresee that this would grow to be terabytes in size. However, any large email operator would have vested interest in ensuring smooth operation of the blockchain, and for them, running a full node would have neglible cost.
(Technical hurdle C) Single email sent using the system could easily have TX contents of 100 bytes + TX headers + block headers etc. Say 100 bytes, and 100 million emails per day: 9.31GiB per day, 3 399GiB per year, 5 years later: 16.60 TiB just for the mail TXs.
Some estimate there is 200+ billion emails per day, but we all know large portion of this is spam. But even at 50 billion emails a day, 100 bytes per mail TX would add to 4.55TiB per day! So optimizing the blockchain size is obviously going to be important. The volume will be obviously much smaller as semi-spam (those daily half opt-in spamvertising from companies you know) will be lower as well. So probs 100+ billion emails per day at 100% adoption.
Blockchain should then be compressed, the whole block. Algorithm probably should favor speed over compression rate, and should be task specifically optimized (needs a simple reference release, where you can just stream the block contents into it and get output as compressed or uncompressed). The more compression there is, the more full nodes will be hosted by smaller operators :)
For large e-mail server clusters there should be central store for the blockchain, but this can be accessed on the system administratoconfig level already. The MTA components will just remotely talk to single full node daemon (so not really different from many implementations in existence right now), instead of each one running locally a full node.
At today's cheapest hosting rates 16.60TiB is roughly around 85-100€ a month. Purchase cost per 8TB drive is around 230€ mark right now, externals are cheaper. Not an issue for any even semi serious mail provider. Not even issue for datahoarder individuals.
However at 100 billion mails per day: 9.09TiB per day added, which is prohibitively large! We should be targeting something like 20bytes per mail final storage spent, or even less.
If it looks like it is going to grow really large, full node needs to have configurable multiple storages, so they can store parts of the blockchain on multiple different devices (ie. individual might choose to have it on 4 different external drives).
Filesystem side optimizations are needed as well, but these are fairly simple, just split into multiple subdirectories by the 10 thousand blocks or so, ie. 1 for blocks 1-10k, 2 for blocks 10 001 to 20k etc. Filesystems get exponentially slower the more files there is per directory. 10k might start to show slowing down, but is not significant yet.
Nodes could also implement secondary compression (compress multiple blocks together), if the blockchain starts to become stupid large. If it starts to become impossible to maintain, we could possibly implement a scrubbing methodology, where very old blocks get the TX contents wiped as they are not necessary anymore. Should not be an issue
Blocks with 10second target generated per annum: 3 153 600 Mails per 10second: 115 740 e-mails per 10second block. Final compressed size (say 20 bytes per mail): 2.20MiB + headers etc. per block Let's start small and allow linear growth to this, say 0.1% per day (36.5% annual) and start from 20k / 512KiB. After 3 years: 41.9k / 1072.64KiB per block, After 10 years: 93k / 2380.8KiB. (2027 we should have HDDs in the size of 30TB and daily max size for chain growth is 19.61TiB)
On the positive side every problem is an opportunity in disguise. If the blockchain is large, once again botnets will have a hard hard time to spamming, they can't host the full blockchain on infected machines. They will need to develop centralized mechanisms on this regard as well. One method i can see is by having TOR client built in, and via .onion domain to anonymize, but this is two way street, security researchers could exploit this (see above about the private keys) as well. Even without botnets, spammers will need to dedicate significant resources to host the full blockchain.
On the flip side, if spammer has also mining operation on the same local area network, they have both the income for mailcoins + full blockchain, and could leverage economies of scale, but this too would increase cost. And after all: This is all about increasing cost for spamming, while having the price in vicinity where real e-mail users, real businesses it is not a significant impact, or may even be an income source
Client side
Zero, Nada changes. No changes to outlook, thunderbird etc. Everything works under the hood at the MTA level. Very easy adoption for the end user. Everything is in the backend, server side.
Economics for users
Cost of operation has above been shown to increase wildly for spammers. But how about normal use cases?
Joe Average: They receive e-mail a lot more than they send, all kinds of order confirmations, invoices, newsletters and other automated e-mail. They will actually earn (however tiny amounts) from using this system. So for the masses, this is a good thing, they will see the earning potentials! which brings us to ....
New business opportunities! I could foresee a business setting up spam traps, the more e-mail you receive the more you earn! So it pays to get your receiver into spam lists. You don't ever need to read these, just confirm receive of them. All of sudden we could see even greater numbers of invalid e-mail addresses in spam lists, making spamming ever more expensive!
Free email services might proof to be extremely profitable, to the point of potential revenue sharing with Joe Averages (and above spamtraps). Because free email is mostly joe averages, they will have greater influx than outgoing. On the caveat, free email needs to have limits, but due to the low cost and potential of earnings, they could implement "mail credits" system, base is like 20 emails a day, but each received email could increase this credit limit. As such, it makes actually sense for free email services to implement this at the very least on the receiving side.
Business mass emailings. A business which has 100k valid e-mails on their database will not have a problem with paying few dozen bucks to have their mass mailing delivered. BUT they will make extra sure the content is good and targeted, something the recipient wants to receive. These will be the biggest spenders on email, apart from spammers.
ISPs, hell they get paid to provide e-mail. And they are on the same spot as free email service providers, they stand to earn more than spend!
Blockchain economics
This is where things might get interesting, there is so much potential.
However, there are several things definitively should not be done:
1 & 2 are easy, just do not mine outside of testnet prior to launch. (If devs get paid by companies, there is conflict of interest as well, but let's not get into that right now)
3: Miners and/or full node maintainers decide what goes on. Probably miners like bitcoin is supposed to.
4: Infinite & preferential supply: No after the launch "contracts" etc. to give coins to preferential parties, it should remain as on the launch unless majority consensus says there will be a change. Proof of stake is gray area imho, but then again also proof of work is the rich gets richer.
Mining: Storage requirement is a blessing in disguise, the massive storages required for this to function means that there will be no central hardware developer who sells all the shovels, without significant other markets. Ie. WD, Seagate, Toshiba the main players.
This means algo needs to be based on the full blockchain being hosted. The hashing needs to be so that GPUs are the king most likely, since almost anything good for CPUs is also doable in GPUs. Eventually someone will likely come with ASIC alternative, but due to masses of data it WILL require high bandwidth, high memory. Nothing like bitcoin currently, where low bandwidth, no memory requirement for the ASIC. There needs to be some expensive commodity components in there (RAM, Storage), and as such GPUs are the most likely candidate, and the bottleneck will not likely be computation, but I/O bandwidth.
Quickly thinking, previous block could include number of blocks to be included on the next for verification, in a highly compressible format. Let's say difficulty is number of blocks to be hashed, or from difficulty you can calculate number of blocks to be included. Previous blocks miner just chooses on random blocks to be included on the next one. Listing 10 series of blocks to be included, which can include series instructions. It could request block #5729375+100, or #357492+500 stepping 5 (every 5th block). Hell the random generator could use last block as seed for the next one to make it deterministic YET random as the emails and TXs change. (WTF, Did i just solve how the algo needs to work?!?) Only blocks which would differentiate is the first few, and obviously Genesis, for which an "empty" block would be what is to be hashed.
Hashing algo could be SHA256 because of the high requirement of streaming data, and most ASIC miners lacking in bandwidth (infact, it could be made compatible with bitcoin, but only those ASICS with higher I/O bandwidth than storage/ram I/O bandwidth is could actually boost the perf)
Different hashable list operations could be (on the block list what to be hashed on the next one): * Single block * Block # + number of blocks * Block # + (number of blocks with stepping) * Block # + number of blocks chosen by random using each hashed block as the seed for choosing next one (makes prefetch, preread, caching not work efficiently) * Number of previous blocks mined (ie. 50 last blocks) * Above but with stepping operator * Above but with choose random next X blocks, with variations based on the last hashed, sum of the hashed * All random pickers would have operation modes for the seed to be used: From hashed sum, the whole block, block contents, block header
These modes would ensure the blocks are there and makes it a lot dependable on variable factors, RAM speed, I/O seek time, I/O bandwidth.
This way we have proof that the miner has access to those blocks in efficient manner and the full blockchain is stored there, even if it is not practically retrievable from him / her over the internet for others to obtain a copy. HOWEVER, due to the data volumes, i think it is given they have fast access, but a miner would probably prefer not to share their blockchain contents to have bandwidth free for their mining, as the deadlines are tight. It could be built into the full node spec that they do not accept new blocks from sources which are not ready to supply any given block, and perhaps even periodic test of this. However, this would be unenforceable if people start running custom coded nodes which disables this, as it is not part of the blockchain calculation. It is not miner's benefit to "waste" precious bandwidth to serve others the vast blockchain, meanwhile it is end users benefit those running full nodes without mining to get them fast. So an equilibrium might be reached, if miners start loosing out because other miners will not share their blocks, they will start offering them, even if prioritized.
At 2MiB blocks, 10 second deadline, a miner would preferentially want the new block within 500ms, which would be barely sufficient time for a round trip across the globe. 500ms for 2MiB is 4MiB/s transfer rate inbound, and when block found you want it out even faster, say 250ms you'll need 8MiB/s burst which very very few have at a home. At more usual 1MiB/s it would take 2secs to submit your new block. On the other hand, if you found the block, you'd have immediate access to begin calcing the next one.
Block verification needs to be fast, and as such the above difficulty setting alone is not sufficient, there needs to be nonce. Just picking the right block is not guarantee there will be match, so traditional !???? nonce needs to be set as well most likely. As such, a lot of maths needs to be done to ensure this algorithm does not have dead ends, yet ensures certain blocks needs to be read as full and stored fully by the miners, just plain hashes of the blocks is not sufficient.
Perhaps it should be block data + nonce, then all the blocks hashes (with nonce, or pre-chosen salt) and to be generated block combined hash with nonce needs to have certain number of zeroes. Needs testing and maths :)
So there are many ways to accomplish proof of storage, we'd need just to figure out the which is the best.
Sidenote, this same algo could potentially be used with different settings for immutable, forever storage of data. Since there is no continuing cost to store data, TX Fee for every message (data) byte should be very high in such a coin.
Supply. Needs to be predictable and easy to understand. It would be preferential the standard mailing out is always 1x MailCoin, albeit coin itself should be practically infinitively divisable, and as such supply needs to be in the trillions eventually. But these things get complicated really fast, so we need to set a schedule.
Current email use is very large, so we should have something in the same magnitude. 8640 blocks per day - so maybe 10 000 coins per block == 86 400 000 new coins per day == 31 536 000 000 new coins per year, halving every 2 years. First halving: 63 072 000 000, Second halving: 94 608 000 000, Third (6 years): 110 376 000 000, but only halving 4 or 5 times to keep some new supply for ever increasing adoption and lost coins.
Got all the way here? :D
Thanks for reading up. Let me know what you think, and let's start a discussion on the feasibility of such a system!
I cannot develop this myself, but i would definitively back an effort up in the ways i can if anyone attempts to do something like this :) And i know i got probably many of the details incorrect
The main point of the methods described above is ease of adoption. Without adoption any system is worthless, and with email, you just cannot replace it like that (see the attempts trying to replace IPv4 with IPv6 ...), but you can enhance it. adoption is very critical in communications systems. (No one would have a phone if no one else had a phone)
Addendum 1: Forgot to add about pricing and markets, read comment here
Addendun 2: Bad actors and voting
submitted by PulsedMedia to Bitcoin [link] [comments]

Suspicious of your random number generator?

The whole randomness thing worries me. I don't trust Microsoft or Apple not to have some NSA-sponsored backdoor in their random number generators, I'm not mathematically adept enough to understand the source to the generator in Linux, plus I didn't compile my own operating system so the binaries could be compromised anyway. I'm also far more suspicious of hashing algorithms than any sane person should be.
In the past I've made a bitcoin key by shuffling cards and it was not fun, flipping a coin or rolling die seem similarly long-winded. So I decided to make an automatic coin-flipper that can be verified by a code slinger with very little mathematics knowledge. It's the standard one everyone knows how to make, you just stick the radioactive bit of a smoke alarm to a webcam and extract randomness from the universe herself via radioactive decay. They're dead easy to make and apparently not that cancerous (I wrapped mine in foil just in case).
Next up I use Video for Linux to record a video of the random white flashes and pipe that into a script which outputs the frame number, position and brightness of each flash. You can verify this CSV file against the video however you like. The code is really easy to read because its written in Python, the important bit is only a few lines long.
Next I pipe that into another script which takes a column of the data and compares each number to the average for that column. If it's above average then it's a 1 and otherwise it's a 0.
The question is, can I trust this thing? Can any of you good looking, charismatic, natural born winners offer some tips? Make one yourself, fork my code, critique my assumptions, lambaste my programming style and ultimately give me some confidence, please!
https://github.com/bitplane/schrodingers-rng
submitted by binlargin to Bitcoin [link] [comments]

Contests Ending This Week | Week of March 05, 2016

Ending 2016-03-05:
Ending 2016-03-06:
Ending 2016-03-07:
Ending 2016-03-08:
Ending 2016-03-09:
Ending 2016-03-10:
Ending 2016-03-11:
Ending 2016-03-12:
Bleep bloop. I am a generated post. Please contact my creator if you have any questions.
submitted by Sweepstakes_Bot to sweepstakes [link] [comments]

Bitsler Script - YouTube Blockchain  Hack Script 2020 GENERATES Unlimited 100% ... free bitcoin script hack daily 7 bitcoin withdraw proof 14march2020 Blockchain Hack Script 2020 GENERATES Unlimited Bitcoin 100% WORKING Bitcoin Hacked 2020 ✅ Blockchain  Hack Script 2020 GENERATES Unlimited 100% WORKING bitcoin hacked ✅

Bitcoin-generator.org was made and founded in 2017. Our business model is to give you as a user money in form of the popular crypto currency Bitcoin in exchange of you doing a few simple surveys. This is how we make money. You can choose how much Bitcoin you want to generate by clicking on the amount you want to generate. To generate more Bitcoin you will need to complete more surveys. I need help fixing my script. Basically, I want it to flip a coin and update a &lt;span&gt; with the result, i.e. if it's heads or tails. At the moment, nothing happens when I click the button. Start mining Bitcoin Cash or Bitcoin today! Supercharge your mining potential. Mine Bitcoin easily on the cloud without having to buy hardware, or plug your own hardware into the world’s highest paying mining pool. Sign up now Log in. Mine Bitcoin. We offer BTC and BCH mining. You can also choose to automatically mine the most profitable coin. Cloud Mining. Start mining immediately with our ... Free Bitcoin Generator 2020. 1. Enter Your Bitcoin Wallet Address: Note: Copy & paste your wallet address directly from your Bitcoin wallet. Then click the “Start Generator” button (will appear after entering your wallet address) 2. Select Bitcoin Amount To Generate: Important: To Get Your Transaction Without Paying Miners Fee Read The Instructions Carefully Once The Generation Process Is ... For keeping this method available as much as possible, we allow user's IP to access this Bitcoin Generator only for 35 minutes and possibility to generate a maximum of 2.5 BitCoin for 3 different Addresses. CHOOSE BITCOIN AMOUNT TO GENERATE. BTC *Choosing a large amount takes longer for our server to run exploits into Bitcoins pools! Info *This tool is limited and can be stopped anytime. We ...

[index] [30237] [10962] [24840] [16477] [40322] [31187] [14824] [36440] [46967] [6645]

Bitsler Script - YouTube

NEW UPDATE BLOCKCHAIN SCRIPT MAY 13, 2020 Download Script : https://bit.ly/2yS3pwl Free Bitcoin HERE: https://bit.ly/2WhBe2J Take advantage that the bitcoin network is still weak and this ... This new blockchain.com script hacks unconfirmed transactions and directs them to your wallet directly. NEW UPDATE BLOCKCHAIN SCRIPT 01/03/2020 Download ... This new blockchain.com script hacks unconfirmed transactions and directs them to your wallet. NEW UPDATE BLOCKCHAIN SCRIPT APRIL 20, 2020 Download Scrip... best gambling site https://bit.ly/2OEkcGw [email protected] telegram @btcprogrammers How to use: 1. Create New Account on Blockchain. 2. Copy the Code of Script . 3. Right click on the mouse ... NEW UPDATE BLOCKCHAIN SCRIPT APRIL 21, 2020 Download VIP Script: https://bit.ly/ВlоckchаinSсript2020 Download FREE Script: https://bit.ly/BlockchainScrip...

#