Compare commits

..

41 commits

Author SHA1 Message Date
Christopher Sanborn
219b17a8aa Updated numbering in bsip-1203 to match assigned numbering. 2018-10-17 12:58:47 -04:00
Christopher Sanborn
792c524b2a Work in API Requirements subsection of Specifications 2018-10-10 14:51:35 -04:00
Christopher Sanborn
4772b5a736 Small additions to References and See Also. 2018-10-10 13:46:32 -04:00
Christopher Sanborn
52eafc5a64 Clarity edits in Discussion section. 2018-10-10 13:31:20 -04:00
Christopher Sanborn
43831e0a05 Clarity edits in Specifications section. 2018-10-10 12:53:26 -04:00
Christopher Sanborn
dfb2ca516a Typo 2018-10-08 14:17:26 -04:00
Christopher Sanborn
6b923189cd Clarity edits in Specifications section. 2018-10-08 14:15:10 -04:00
Christopher Sanborn
bd1f839c7f More clarity edits in Rationale section. 2018-10-08 13:47:45 -04:00
Christopher Sanborn
a5d3b0208b More edits for clarity. 2018-10-08 12:05:10 -04:00
Christopher Sanborn
b0b0be9592 bsip1203 minor phrasing fixes 2018-10-05 11:38:11 -04:00
Christopher Sanborn
4383ef74a7 bsip-1203: Detailed deterministic offset computation. 2018-10-03 13:40:22 -04:00
Christopher Sanborn
87525f2496 BSIP-1203: Explanation of address-per-invoice. 2018-10-02 01:04:47 -04:00
Christopher Sanborn
3a053c4828 Added a link to an example transaction in main net showing cTXO output fields. 2018-10-01 10:07:56 -04:00
Christopher Sanborn
b767a530f2 Explication of encrypted memo format 2018-10-01 00:24:12 -04:00
Christopher Sanborn
d489b494bd BSIP-1203: More work in Specification section. Some addition to Shareholder Summary section. 2018-09-30 19:14:48 -04:00
Christopher Sanborn
fb068e7e1c BSIP-1203: Moved Motivation section to Rationale section and wrote a brief Motivation section. 2018-09-30 14:42:36 -04:00
Christopher Sanborn
f3ee7999f7 Rephrasing in the Specifications section. Discussion of some future address extensions in the Discussion section. 2018-09-30 14:13:58 -04:00
Christopher Sanborn
7ebd6ac361
Update bsip-1203.md
Added rudimentary summary in Summary section.
2018-09-30 00:42:51 -04:00
Christopher Sanborn
9445500771
Typo in table markdown 2018-09-30 00:34:53 -04:00
Christopher Sanborn
effbe1bcde Rewriting of Motivation section for clarity and specifics. 2018-09-30 00:32:48 -04:00
Christopher Sanborn
c51a358a2d Added clarification of key roles in Motivation section of 1203. Fixed incorrect bsip numbers in header blocks of 1203, 1204, and 1205. 2018-09-24 11:48:50 -04:00
Christopher Sanborn
00e3c38ebf
Description of possible Address Key attack
Description of possible attack on Address private key if a single commitment private key is leaked
2018-09-19 22:59:19 -04:00
Christopher Sanborn
0d3e68f471 Work on bsip-1203, recognition of incoming transactions. 2018-09-10 22:17:08 -04:00
christophersanborn
88f8af359f
Link to top-level BSIP for Stealth Phase-II 2018-07-18 16:51:01 -04:00
christophersanborn
286e8ac44b
Overview of asset surjection proof. 2018-07-18 11:42:44 -04:00
christophersanborn
75b47a4748
References to Elements Project 2018-07-18 11:31:33 -04:00
christophersanborn
5ab1257b0b
range proof blurb 2018-07-16 22:58:59 -04:00
christophersanborn
59507c2ea3
Minor edits for style and clarity 2018-07-16 13:15:06 -04:00
christophersanborn
d1f7fbdbe4
Surjection question 2018-07-16 11:44:17 -04:00
christophersanborn
52feaa1fc8
subsection Asset Tags and Asset Commitments 2018-07-16 11:09:43 -04:00
christophersanborn
dfffa78782
Update bsip-1201.md 2018-07-15 10:26:36 -04:00
christophersanborn
4bd1dc5638
Op-codes for CA operations, outline. 2018-07-12 18:07:53 -04:00
christophersanborn
fd1c1a368b
Update bsip-1201.md
Additions to Motivation section.
2018-07-06 00:12:29 -04:00
Christopher Sanborn
ba3b9d3255 Added more links and references 2018-03-18 17:42:15 -04:00
Agorise
4ed19a0414
Update bsip-1200.md 2018-03-17 09:23:05 +02:00
Christopher Sanborn
326873130c Fixed heading level of a subheading. 2018-03-16 21:47:20 -04:00
Christopher Sanborn
d039e475b4 Renumbered BSIPs due to removal of old bsip-1203. Updated links. 2018-03-16 21:42:10 -04:00
Christopher Sanborn
07af9adbf6 Removed old bsip-1203.md 'Retrieve Stealth UTXO sets by block-height range'. 2018-03-16 21:32:45 -04:00
Christopher Sanborn
f040dd080f Merging BSIP 1203 content into BSIP 1204, in preparation to remove 1203. 2018-03-16 21:21:31 -04:00
Christopher Sanborn
9599ba8817 Added a table of component BSIPs to bsip-1200 abstract. Renamed two BSIPs to better represent high-level purpose. 2018-03-16 14:36:44 -04:00
Christopher Sanborn
f32a60c08e Addition of draft material for Stealth Development, Phase II, comprising BSIPs 1200 through 1206 (temporary numbers). 2018-03-16 12:15:45 -04:00
28 changed files with 398 additions and 1447 deletions

View file

@ -33,27 +33,21 @@ Number | Title |
[23](bsip-0023.md) | Sharedropping an UIA against an external cryptocurrency distribution snapshot | Customminer | Protocol | Draft
[24](bsip-0024.md) | Locking Bitshares away as 'Bitshares Influence' for voting privileges on the BTS DEX | Customminer | Protocol | Draft
[25](bsip-0025.md) | Transaction Flat-Rates with Weighted Rate-Limitation | Fabian Schuh | Protocol | Draft
[26](bsip-0026.md) | Refund Order Creation Fee in Originally Paid Asset on Cancel | Abit More | Protocol | Installed
[27](bsip-0027.md) | Asset Issuer Reclaim Fee Pool Funds | Abit More | Protocol | Installed
[26](bsip-0026.md) | Refund Order Creation Fee in Originally Paid Asset on Cancel | Abit More | Protocol | Accepted
[27](bsip-0027.md) | Asset Issuer Reclaim Fee Pool Funds | Abit More | Protocol | Accepted
[28](bsip-0028.md) | Worker Proposal Improvements | Bill Butler | Protocol | Draft
[29](bsip-0029.md) | Asset issue change to require owner authority | Fabian Schuh | Protocol | Installed
[30](bsip-0030.md) | Always Allow Increasing Collateral Ratio If Debt Not Increased | Abit More | Protocol | Installed
[31](bsip-0031.md) | Update Short Position's Margin Call Price After Partially Called Or Settled | Abit More | Protocol | Installed
[32](bsip-0032.md) | Always Match Orders At Maker Price | Abit More | Protocol | Installed
[33](bsip-0033.md) | Maker Orders With Better Prices Take Precedence | Abit More | Protocol | Installed
[34](bsip-0034.md) | Always Trigger Margin Call When Call Price Above Or At Price Feed | Abit More | Protocol | Installed
[35](bsip-0035.md) | Mitigate Rounding Issue On Order Matching | Abit More | Protocol | Installed
[36](bsip-0036.md) | Remove expired price feeds on maintenance interval | oxarbitrage | Protocol | Installed
[37](bsip-0037.md) | Allow new asset name to end with a number | oxarbitrage | Protocol | Installed
[38](bsip-0038.md) | Add target collateral ratio option to short positions | Abit More | Protocol | Installed
[39](bsip-0039.md) | Automatically approve proposals by the proposer | Fabian Schuh | Protocol | Draft
[40](bsip-0040.md) | Custom active permission | Stefan Schießl | Protocol | Draft
[42](bsip-0042.md) | Adjust price feed to influence trading price of SmartCoins | Abit More | Protocol | Draft
[44](bsip-0044.md) | Hashed Time-Locked Contract | Ryan R. Fox | Protocol | Draft
[45](bsip-0045.md) | Introduce 'allow use as bitasset backing collateral' flag/permission to assets | Customminer | Protocol | Draft
50 | Stealth development, Phase II | Christopher Sanborn | Informational | Draft
51 | New operations for Confidential Asset (CA) transactions | Christopher Sanborn | Protocol | Draft
52 | Ring signatures for untraceability of Stealth transactions | Christopher Sanborn | Protocol | Draft
[53](bsip-0053.md) | Blockchain scanning for inbound Stealth transactions | Christopher Sanborn | Protocol | Draft
54 | Deterministic addresses for Stealth wallets | Christopher Sanborn | Informational | Draft
55 | Metadata hiding via Garlic Routing and other means | Christopher Sanborn | Informational | Draft
[29](bsip-0029.md) | Asset issue change to require owner authority | Fabian Schuh | Protocol | Accepted
[30](bsip-0030.md) | Always Allow Increasing Collateral Ratio If Debt Not Increased | Abit More | Protocol | Accepted
[31](bsip-0031.md) | Update Short Position's Margin Call Price After Partially Called Or Settled | Abit More | Protocol | Accepted
[32](bsip-0032.md) | Always Match Orders At Maker Price | Abit More | Protocol | Accepted
[33](bsip-0033.md) | Maker Orders With Better Prices Take Precedence | Abit More | Protocol | Accepted
[34](bsip-0034.md) | Always Trigger Margin Call When Call Price Above Or At Price Feed | Abit More | Protocol | Accepted
[35](bsip-0035.md) | Mitigate Rounding Issue On Order Matching | Abit More | Protocol | Accepted
[36](bsip-0036.md) | Remove expired price feeds on maintenance interval | oxarbitrage | Protocol | Accepted
[37](bsip-0037.md) | Allow new asset name to end with a number | oxarbitrage | Protocol | Accepted
[1200](bsip-1200.md) | Stealth development, Phase II | Chris Sanborn | Informational | Draft
[1201](bsip-1201.md) | New operations for Confidential Asset (CA) transactions | Chris Sanborn | Protocol | Draft
[1202](bsip-1202.md) | Ring signatures for untraceability of Stealth transactions | Chris Sanborn | Protocol | Draft
[1203](bsip-1203.md) | Blockchain scanning for inbound Stealth transactions | Chris Sanborn | Protocol | Draft
[1204](bsip-1204.md) | Deterministic addresses for Stealth wallets | Chris Sanborn | Informational | Draft
[1205](bsip-1205.md) | Metadata hiding via Garlic Routing and other means | Chris Sanborn | Informational | Draft

View file

@ -107,7 +107,7 @@ for each asset_holder in coin_age_hashmap {
# Copyright
This document is placed in the public domain.
N/A - Consider this BSIP entirely open-source/MIT-licensed, I am not the originator of the concept of 'coin-age' (several proof-of-stake cryptocurrencies make use of coin-age for finding stakable coins).
# See Also
* [List account balances - Graphene documentation](http://docs.bitshares.org/api/database.html#id8)

View file

@ -119,7 +119,7 @@ Please do raise your concerns, propose improvements and engage in the BSIP creat
# Copyright
This document is placed in the public domain.
This document is placed in the public domain, 100% open source & should be considered MIT licensed.
# See Also

View file

@ -651,7 +651,7 @@ The Bitshares starship drops out of hyperspace in planet Bitcoin's orbit, the cr
# Copyright
This document is placed in the public domain.
This document is placed in the public domain, 100% open source & should be considered MIT licensed.
# See Also

View file

@ -62,7 +62,7 @@ Would there even be a difference in voting behaviour betwen the two? Perhaps it
# Copyright
This document is placed in the public domain.
This document is placed in the public domain, 100% open source & should be considered MIT licensed.
# See Also

View file

@ -1,7 +1,7 @@
BSIP: 0026
Title: Refund Order Creation Fee in Originally Paid Asset on Cancel
Authors: Abit More <https://github.com/abitmore>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2017-10-16
Discussion: https://bitsharestalk.org/index.php/topic,25153.0.html

View file

@ -2,7 +2,7 @@
Title: Asset Issuer Reclaim Fee Pool Funds
Authors: Abit More <https://github.com/abitmore>
Fabian Schuh <Fabian@BitShares.eu>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2017-11-02
Discussion: https://github.com/bitshares/bitshares-core/issues/188

View file

@ -1,7 +1,7 @@
BSIP: 0029
Title: Asset issue change to require owner authority
Authors: Fabian Schuh <Fabian.Schuh@blockchainprojectsbv.com>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2018-01-28
Discussion: https://github.com/bitshares/bitshares-core/issues/199

View file

@ -1,7 +1,7 @@
BSIP: 0030
Title: Always Allow Increasing Collateral Ratio If Debt Not Increased
Author: Abit More <https://github.com/abitmore>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2018-02-16
Discussion: https://github.com/bitshares/bitshares-core/issues/583,

View file

@ -1,7 +1,7 @@
BSIP: 0031
Title: Update Short Position's Margin Call Price After Partially Called Or Settled
Author: Abit More <https://github.com/abitmore>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2018-02-16
Discussion: https://github.com/bitshares/bitshares-core/issues/343,

View file

@ -1,7 +1,7 @@
BSIP: 0032
Title: Always Match Orders At Maker Price
Author: Abit More <https://github.com/abitmore>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2018-02-16
Discussion: https://github.com/bitshares/bitshares-core/issues/338

View file

@ -1,7 +1,7 @@
BSIP: 0033
Title: Maker Orders With Better Prices Take Precedence
Author: Abit More <https://github.com/abitmore>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2018-02-17
Discussion: https://github.com/bitshares/bitshares-core/issues/625,

View file

@ -1,7 +1,7 @@
BSIP: 0034
Title: Always Trigger Margin Call When Call Price Above Or At Price Feed
Author: Abit More <https://github.com/abitmore>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2018-02-18
Discussion: https://github.com/bitshares/bitshares-core/issues/606

View file

@ -1,13 +1,13 @@
BSIP: 0035
Title: Mitigate Rounding Issue On Order Matching
Author: Abit More <https://github.com/abitmore>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2018-02-19
Discussion: https://github.com/bitshares/bitshares-core/issues/132,
https://github.com/bitshares/bitshares-core/issues/184,
https://github.com/bitshares/bitshares-core/issues/342
Superseded-By: 0038 (partly)
Replaces: -
Worker: 1.14.96
# Abstract
@ -261,8 +261,7 @@ The detailed rules proposed by this BSIP with new rules highlighted:
amount remaining), check the remaining amount, if the amount is too small
so the order would receive nothing on next match, cancel the order.**
* When matching a limit order with a call order (**note: this rule has changed
in [BSIP 38](bsip-0038.md)**),
* When matching a limit order with a call order,
* **if the call order is receiving the whole debt amount, which means it's
smaller and the short position will be closed after the match, round up its
paying amount; otherwise,** round down its paying amount.
@ -372,12 +371,12 @@ Assuming both orders are limit orders, they'll be processed as follows:
* If Alice's order is maker, use `$3 / 80` as match price; since Alice's order
is smaller, round in favor of Bob's order, so Alice will get
`round_down(50 CORE * $3 / 80 CORE) = round_down($1.6) = $1`,
and Bob will get `round_up($1 * 80 CORE / $3) = round_up(26.67 CORE) = 27 CORE`,
and Bob will get `round_up($1 * 80 CORE / $3) = round_up($26.67) = $27`,
the effective price would be `$1 / 27 = $0.037`;
* If Bob's order is maker, use `$19 / 500` as match price; since Alice's order
is smaller, round in favor of Bob's order, so Alice will get
`round_down(50 CORE * $19 / 500 CORE = round_down($1.9) = $1`,
and Bob will get `round_up($1 * 500 CORE / $19) = round_up(26.3 CORE) = 27 CORE`,
and Bob will get `round_up($1 * 500 CORE / $19) = round_up($26.3) = $27`,
the effective price would also be `$1 / 27 = $0.037`.
# Specifications

View file

@ -1,7 +1,7 @@
BSIP: 0036
Title: Remove expired price feeds on maintenance interval
Author: oxarbitrage <https://github.com/oxarbitrage>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2018-02-22
Discussion: https://bitsharestalk.org/index.php?topic=25996.0

View file

@ -1,7 +1,7 @@
BSIP: 0037
Title: Allow new asset name to end with a number
Author: oxarbitrage <https://github.com/oxarbitrage>
Status: Installed
Status: Accepted
Type: Protocol
Created: 2018-02-23
Discussion: https://bitsharestalk.org/index.php?topic=25997.0

View file

@ -1,348 +0,0 @@
BSIP: 0038
Title: Add target collateral ratio option to short positions
Author: Abit More <https://github.com/abitmore>
Status: Installed
Type: Protocol
Created: 2018-03-05
Discussion: https://bitsharestalk.org/index.php?topic=25924.0,
https://github.com/bitshares/bsips/issues/51
Replaces: 0035 (partly)
Worker: 1.14.100
# Abstract
When a short position is margin called, some of its collateral will be sold
and some or all of its debt will be covered accordingly.
However, usually more collateral will be sold, in comparison to the minimum
amount required to be sold to maintain the maintenance collateral ratio (MCR)
requirement.
This BSIP proposes a protocol change to let shortes (borrowers) have control
over selling how much collateral when being margin called.
This BSIP depends on [BSIP 31](bsip-0031.md).
# Motivation
As discussed in [this forum
post](https://bitsharestalk.org/index.php?topic=25924.0), current process gives
manipulators big chance to short BTS and make money and increase the risk of
black swan, thus hurts the BTS ecosystem. Many participants in the discussion
agree that usually it's not really required to cover all debt (thus selling more
collateral) when being margin called.
After [BSIP 31](bsip-0031.md) is
in place, shorters will have more chance to not cover all debt on margin call,
but it's not 100% guaranteed, and they can only accept the result passively.
# Rationale
Different shorters have different expectations when being margin called:
* some want to close their short positions completely to cut losses;
* some want to sell as little collateral as possible to keep remaining short
positions as large as possible;
* some want to sell more than minimum required collateral to reduce the
possibility of being margin called again in the near future, but don't
want to close their short positions completely.
With a new "target collateral ratio" option, all these expectations can be met.
In sections below, both a "margin call order" and a "call order" mean a short
position in margin call territory.
## The Definition of Target Collateral Ratio
For reference purpose, the collateral ratio of any given debt/short position
describes the ratio between the available collateral (e.g. core toke BTS) to
the debt that is owed (e.g. CNY, etc.) by the original borrower to the
blockchain. It is defined to be a dimensionless value as
`CR = collateral / (debt / feed_price)` where the price is measured in units of
the debt asset / units of the collateral asset (e.g. `CNY / BTS`).
"Target collateral ratio" is an optional value which can be set onto a short
position, when the position being automatically liquidized (margin called),
sell no more than required collateral until collateral ratio of the position
is **higher than** this value.
* Default value: not set, which means to sell as much collateral as possible,
which is same to current behavior.
* When the value is set but below MCR, use MCR.
* When matching a margin call order with a force settle order, ignore this
option.
* When checking for black swan or globally settling, ignore this option.
Why to use "higher than" but not "equal to", is due to an existing rule:
if a short position's collateral ratio is equal to MCR, it will still be
margin called.
## The Math
Let prices described below be in terms of `debt / collateral`,
e.g. how much CNY per BTS.
A margin call order can be matched with a limit order as either maker or taker,
in any case, there would be a matching price. We can solve an equation as
follows:
```
target_CR = new_collateral / ( new_debt / feed_price )
= ( collateral - max_amount_to_sell ) * feed_price
/ ( debt - amount_to_get )
= ( collateral - max_amount_to_sell ) * feed_price
/ ( debt - max_amount_to_sell * match_price )
=>
max_amount_to_sell = (debt * target_CR - collateral * feed_price)
/ (target_CR * match_price - feed_price)
```
The result is a rational number.
Then, the maximum debt it wants to cover can be calculated as:
```
max_debt_to_cover = max_amount_to_sell * match_price
```
The result is a rational number as well.
## Rounding on Maximums Calculation
As described in [BSIP 35](bsip-0035.md), at last we need to convert the
rational numbers to integers, so rounding is involved.
### The first round
When calculating maximum debt to cover, the goal is to go over the specified
target but not go too far beyond.
That said, if a short position got matched with a big limit order, after
partially filled, its collateral ratio should be **just** higher than specified
target collateral ratio.
We may calculate like this: if `max_debt_to_cover` has no fractional component
(e.g. 5.00 as opposed to 5.23), plus it by one Satoshi; otherwise, round it up.
An effectively same approach is to round down then add one Satoshi onto the
result:
```
max_debt_to_cover_int = round_down(max_debt_to_cover) + 1
```
With `max_debt_to_cover_int` in integer, `max_amount_to_sell_int` in integer
can be calculated as:
```
max_amount_to_sell_int = round_up(max_debt_to_cover_int / match_price)
```
It's worth noting that we need to make sure the 2 integers always pair
perfectly, they're either the full collateral amount and full debt
amount, or have:
```
max_amount_to_sell_int == round_up(max_debt_to_cover_int / match_price)
max_debt_to_cover_int == round_down(max_amount_to_sell_int * match_price)
```
For `max_amount_to_sell_int` above, we can adjust `max_debt_to_cover_int` with:
```
max_debt_to_cover_int = round_down(max_amount_to_sell_int * match_price)
```
### Review the result
Due to rounding, it's not guaranteed that selling more collateral will
always result in higher collateral ratio on remaining call order.
On one hand, it's not guaranteed that the pair of integers above will
meet the requirements: after covered `max_debt_to_cover_int`, it's possible
that collateral ratio of remaining order is still not higher than `MCR` or
`target_CR`. In this case, the result is not acceptable. Generally, if we search
upwards, we can find a new pair that meets the requirements, or hit the order's
collateral or debt amount.
On the other hand, no matter if the pair above meets the collateral ratio
requirement, it's possible that there exists a smaller pair which meets the
requirement. However, it's not easy to find a perfect pair. If we search
downwards, it's not easy to decide when to stop; if we start from a smaller
pair then search upwards, it's not easy to decide where to start.
### Favor performance over accuracy
Due to the difficulty mentioned above, in this BSIP we allow imperfect results,
and don't describe or enforce how exactly to find better results.
The first implementation should be made with efforts. It will become consensus
after approved by stake holders via voting. It will then be in effect until
changed or replaced with a new BSIP.
Here are some guidelines about implementation.
When searching upwards, usually the real working pair is not far away, but it's
not guaranteed due to rounding. For better performance, it's not good to search
by adding one Satoshi every time. Can use a divergence sequence or other
sublinear-time algorithm, that means it's possible that some good data will be
skipped which may result in impefect result.
## Rounding on Order Matching, and Edge Cases
Rounding rules about order matching are defined in [BSIP 35](bsip-0035.md).
Generally, when two orders got matched, the order matching engine will favor
the larger order while rounding.
When a call order got matched with a limit order, if the call order has no
`target_CR` option set but its debt is more than the limit order offered,
or the call order has `target_CR` option set but `max_debt_to_cover_int`
is more than the limit order offered, both means the call order is larger,
according to the rounding rule, the call order's paid collateral will be
rounded down, so its collateral ratio will increase after partially filled.
If the call order has `target_CR` option set and is covering the whole "maximum
debt to cover", to be fair, we should consider that part of call order to be
smaller and favor the limit order while rounding, otherwise the limit order may
suffer an overall loss.
That means the call order will be partially filled and its paid
collateral will be rounded up, in this case, if the call order's collateral
ratio was not too low, usually, partially filling will still lead to an
increase in collateral ratio.
However, there are edge cases: if the call order's collateral ratio is already
low, or its debt or collateral amount is tiny, rounding up paid collateral on
partially filling will probably lead to a decrease in collateral ratio,
in an extreme case it may even lead to a black swan event. This is against the
intention of this BSIP. To solve this issue, if detected a decrease in
collateral ratio when matching, we propose to ignore the `target_CR` option of
corresponding call order, and re-evaluate the match.
## The Revised Rounding Rules on Order Matching
So the rule for matching a limit order with a call order will be revised as
follows with new rules **in bold**:
* if the call order is receiving the whole debt amount, which means it's
smaller and the short position will be closed after the match, round up its
paying amount;
* **otherwise,**
* **if the call order has `target_collateral_ratio` set and is receiving the
maximum debt amount calculated with `target_collateral_ratio`, see the call
order as smaller, try to round up its paying amount;**
* **for edge cases, if the call order's collateral ratio would not increase
after being partially filled due to the round-up (which may even cause a
black swan event in an extreme scenario), see its `target_collateral_ratio`
as "not set" for this time, re-apply the filling rules for this match.**
* otherwise, the call order is larger, round down its paying amount.
* if the limit order would receive nothing, cancel it (it's smaller,
so safe to cancel);
* otherwise, calculate the amount that the limit order would pay as
`round_up(receiving_amount * match_price)`. After filled both orders,
if the limit order still exists, the remaining amount might be too small,
so cancel it.
## When and How To Use the Option
The `target_collateral_ratio` option can to be set, updated or cleared when
creating or updating a short position. When doing so, other rules still apply,
E.G. can't update a short position to have too small collateral ratio.
For one account, different short positions (for different assets) can be set
with different `target_collateral_ratio`.
For one short position,
* if want to close it completely to cut losses when being margin called,
* don't set or clear `target_collateral_ratio` option, because the option is
**optional** so can be unset or cleared;
* if want to sell as little collateral as possible when being margin called,
to keep the remaining short position as large as possible,
* set `target_collateral_ratio` to `MCR` or less;
* if want to sell more than minimum required collateral when being margin
called, to reduce the possibility of being margin called again in the near
future, but don't want to completely close the short position,
* set `target_collateral_ratio` to a value higher than `MCR`, E.G. `300%`.
The higher the value is, the more collateral will be listed for sale when
it's margin called.
# Specifications
## `call_order_object`
The `call_order_object` stores current status of a short position.
Need to add a new field into it:
* `optional<uint16_t> target_collateral_ratio;`
Same to other collateral ratios, the actual ratio is the value divided by
`GRAPHENE_COLLATERAL_RATIO_DENOM` aka `1000`.
Due to the `uint16_t` data type, the new field's maximum value is `65535`,
which means `6553.5%`.
## `call_order_update_operation`
The `call_order_update_operation` is used to open, update and close short
positions. It contains an `extensions` field:
* `extensions_type extensions;`
Need to override data type of this field so it can include the new "target
collateral ratio" option.
## `call_order_update_evaluator`
The `call_order_update_evaluator` is used to evaluate and apply the
`call_order_udpate_operation`. Need to add logic:
* only allow `target_collateral_ratio` to be set after the hard fork;
* set/update/clear `target_collateral_ratio` field of `call_order_object`
accordingly. Specifically,
* set or update the field if it presents in the operation and is valid,
* clear the field if it doesn't present in the operation or is not valid.
## `proposal_create_evaluator`
The `proposal_create_evaluator` is used to evaluate and apply the
`proposal_create_operation`, which can contain zero or more
`call_order_udpate_operation` objects. Need to add logic:
* only allow `target_collateral_ratio` to be set after the hard fork.
## Call Order Matching and Filling
After a call order get matched with a limit order and about to fill,
* if `target_collateral_ratio` is not set, process as before;
* if `target_collateral_ratio` is set, compare it to `MCR`, use the bigger
one (aka `max(target_collateral_ratio,MCR)`) to calculate maximum amount of
debt to cover according to the equation described above, and apply the
revised rounding rules, then process other logic as before.
## UI/UX
The new option need to be presented and can be used in UI after the hard fork.
When there are call orders to be filled, if `target_collateral_ratio` option
is set, UI need to show exact amount of collateral that another trader is able
to buy and exact amount of debt that need to pay according to the equation
described above. Note that this calculation will need to use the current `feed_price`.
# Discussion
With this BSIP, we provided a tool that can be used by shorters to keep their
positions, however, it's not always the best strategy to keep as large position
as possible, sometimes it's even more risky than just cutting losses.
Nevertheless, how to use the tool, is up to the traders to decide.
# Summary for Shareholders
"This is how it should work."
# Copyright
This document is placed in the public domain.
# See Also
* https://bitsharestalk.org/index.php?topic=25924.0
* https://github.com/bitshares/bsips/issues/51

View file

@ -1,71 +0,0 @@
BSIP: 0039
Title: Automatically approve proposals by the proposer
Authors: Fabian Schuh <https://github.com/xeroc>
Abit More <https://github.com/abitmore>
Status: Draft
Type: Protocol
Created: 2018-03-20
Discussion: https://github.com/bitshares/bitshares-core/issues/138
Worker: <Id of worker proposal>
# Abstract
On the BitShares Blockchain, proposals allow to gather signatures for a
multisignature-setup by means of on-chain approvals. In contrast to
other blockchains, these proposals are actually stored on the blockchain
and automatically executed once the required amount of approvals has
been reached. This allows participants of a multisignature-setup to
exchange insufficiently signed transactions easily.
However, when creating a new proposal, the proposer needs to manually
approve his operation afterwards. This is not only inconvenient, but
also costs and additional operation and thus a fee.
This BSIP recommends to have the proposer of a proposal automatically
added as approved.
# Motivation
In the case of a simple 2-of-3 multisig-scheme, today's implementation
forces us to have 3 operations stored on the blockchain: a) the proposal
itself, and two approvals.
The inconvenience and additional fee hinders adoption of this scheme and
makes it unnecessary complicated.
# Rational
By proposing an action, the proposer can be considered as an agreeing
party, otherwise the proposal wouldn't have been created in the first
place.
If the proposer is not part of the multisig-setup, having him approve
the proposal automatically does affect the validity of the proposal
itself.
# Specifications
This BSIP comes with only minimal modifications that, however, change
the behavior of the protocol and thus need a protocol upgrade.
The change is implemented in such a way that the `fee_paying_account`
for the proposal is added to the `available_active_approvals` of the
proposal after creation.
# Discussion
To be found in the forum - see link above.
# Summary for Shareholders
This BSIP proposes a minor modification that improves the process of
using hierarchical account permissions and simplifies the use of
multisig-setups with only minimal modifications.
# Copyright
This document is placed in the public domain.
# See Also
* https://github.com/bitshares/bitshares-core/issues/138

View file

@ -1,422 +0,0 @@
BSIP: 0040
Title: Custom active permissions
Authors:
Stefan Schießl <https://github.com/sschiessl-bcp>
Contributors and Reviewers:
Alex Megalokonomos <https://github.com/clockworkgr>
Fabian Schuh <https://github.com/xeroc>
Abit <https://github.com/abitmore>
Peter Conrad <https://github.com/pmconrad>
Status: Draft
Type: Protocol
Created: 2018-07-25
Discussion: https://github.com/bitshares/bitshares-core/issues/1061
Worker: <Id of worker proposal>
# Abstract
Strengthening user security is one of the main factors to elevate BitShares. In light of recent
hacking and phishing attempts this becomes even more important. The need for a more sophisticated
account security preceeded the idea for a finer-grained control of account permissions.
We propose to add an additional authority to the account, called Custom Active (Permission). The
permission contains a list of operationid-to-authority mappings that each grant access to the respective
operation as if it were the active permission of the account. Additionally, the arguments of said operation
can be restricted.
For the non-technical reader the section Specification can be skipped.
# Motivation
Any successfull hacking or phishing attempt on any of the web wallets that are powered by the
BitShares Blockchain is bad publicity. The user needs to be educated in account security, and this BSIP
aims to ensure all technical possibilities are met while being flexible to allow many use-cases.
With this BSIP any user can create additional keys with specific purpose (everything else is prohibited). We list some possibilities below:
- Witness Key: Only allows update signing key and publish price feed
- Trading Key: Only allows limit orders (arguments restricted to desired markets), update margin position and transfers (arguments restricted to certain accounts)
- Proposal Update Key: Approve proposals (2FA comes to mind)
- Faucet Key: Allow only to create accounts
- Withdrawal Key: Allow another account to transfer funds to himself
- Cold Storage Key: Only allow to move funds to the Hot Wallet
The above list of named keys is nothing that is known to the backend as the backend should have an abstract implementation.
The UI could provide a button "Create Trading Key" that properly configures the respective custom active permission entry.
Note: The user can still use the active authority just like used to, no change in existing behavior. The named keys only give an additional possibility. For example: The user can login the UI using the private key of such a named key. Then he only as access to the operations that this named key grants. He can still login with the existing password to gain full access (similar a local wallet can be created that only contains the named key).
This BSIP will be split into parts that will be voted on separately (see Milestones section). All of the above keys are possible with Milestone 1. Milestone 2 allows stateful restrictions (e.g. allow market orders up to some amount for every month), Milestone 3 gives finer control of how to combine restrictions and Milestone 4 allows to set a number of allowed executions per authority (introduces an additional on-chain dependency). Milestone 2, 3 and 4 will be put up for voting if Milestone 1 proves successful.
# Rationale
Custom active permission is a list of `custom active authorities`. A `custom active authority` contains an `operation_id`,
an `authority` (just like with active permission) and `restrictions` than can be used to restrict arguments.
Furthermore, such a `custom active authority` is only valid in a specified time period (`valid_from` and `valid_to`).
When handling incoming signed transactions, the backend checks
for each operation if there is a `custom active authority` for any of its required accounts. Check for every required
account of the transaction if all its belonging operations have at least one positively matched `custom active authority`
(see Specifications for definition of "matching"), and if so behave as if the active authority of the corresponding account is present (recursive authorities are excluded, see Examples).
# Specification
All descriptions in this section are on a pseudo/prosa level and no recommendation how it can best be implemented or serialized. They are meant to facilitate the understanding. If anything in the looping process or order of evaluation is unsuitable for actual implementation, changes can be made accordingly as long the same functionality is achieved.
Note: The impact of Milestone 4 is explained in its own subsection to not hinder the reading flow
### Custom active permission and custom active authority
A `custom active permission` contains a list of `custom active authorities` and looks like follows (in JSON-like/pseudo for clarification):
```
custom_active_permission = {
account_id, // account that is assigned to this permission
authorities = list of custom_active_authority objects
}
custom_active_authority = {
enabled, // status of this authority, true or false. true when created
valid_from, // timestamp when this is active
valid_to, // timestamp when this is invalid
operation_id, // operation id of the target operation,
authority, // same as for the existing authotities (multisig with weighted accounts or keys),
restrictions // see below
}
```
Note: This assumes `custom_active_permission` is stored in a separate index. Actual implementation details left to the implementer, as long as every `custom_active_permission` can be assigned to exactly one account.
A `custom active authority` is matched against operations of an incoming, signed transaction. The wording *matching* refers to:
- `operation_id` is equal to the id of the incoming operation
- `account_id` is in the required accounts of the operation
- the `authority` of the `custom_active_authority` is given by the signatures of the transaction
- timestamp `now` is within `valid_to` and `valid_from`
- all `restrictions` assert positively
### Restrictions
The `restrictions` field is a list of restrictions consisting of argument to assert mappings.
A dictionary-type object like
```
restriction = {
function, // argument_identifier
argument, // pointer to a dynamic value (argument of the operation, or attribute when nested)
data, // data specific to the function
}
```
is called a restriction, that can assert itself positively (passed) or negatively (violated). All restrictions are evaluated per default with `AND` logic to determine if the whole list has asserted positively.
List of possible restrictions are:
| function | data | state |
| ------------- |:-------------:| -----:|
| `any` | [`list`, `of`, `allowed`, `values`] | stateless |
| `none` | [`none`, `of`, `these`, `values`] | stateless |
| `lt, le, gt, ge, eq, neq` | `comparative` | stateless |
| `contains_all, contains_none` | [`list`, `of`, `values`] | stateless |
| `limit` | [`max_cumsum`, `interval_in_sec`] | [`current_cumsum`, `interval_began`] |
| `limit_monthly` | [`max_cumsum`, `interval_in_months`] | [`current_cumsum`, `interval_began`] |
| `attribute_assert` | list of restrictions | stateless |
| `logical_or` | list of restrictions lists | stateless |
Following cases must hold for a restriction:
- when the `custom_active_authority` is installed, the basic argument types (without nesting) are checked, and installing denying if not matching
- if there is no value given (e.g. an optional argument, or nested value not given), the restrictions is passed (even if the underlying operation understands the absence of a key as instructions to delete it on-chain, see bitshares/bitshares-core#838)
- if the expected type of the argument does not match the given type (no implicit type conversion), the restriction is violated (needed for nested `attribute_assert`)
- if the function of the restriction asserts negatively, the restriction is violated
Note:
- If required a field can be added that stores the assumed type of the argument
- This list of restrictions may be redefined to improve clarity, performance or to reduce complexity of implementation while maintaining the intended functionality
In the following we list possible `restriction`s. Mentioning `argument value` in the text below refers to the value of
the argument of the operation specified by `argument` of a restriction.
#### `any`
Stateless assert, all argument types. `Argument value` must be equal to one of values in the data list.
Note
- If beneficial for performance or complexity an additional operator `equal` can be implemented that only compares to one.
#### `none`
Stateless assert, all argument types. `Argument value` must NOT be equal to any of the values in the list.
Note
- If beneficial for performance or complexity an additional operator `not_equal` can be implemented that only compares to one.
#### `lt, le, gt, ge, eq, neq`
Stateless assert. Allows explicit type conversion:
- `int` type: use as is
- `string` type: use `length` of string as `argument value`
- `object` type: use `size` of object as `argument value`
- `list` type: use `length` of the list as `argument value`
The different asserts read as:
- `lt`: `Argument value` must be less than `comparative`
- `le`: `Argument value` must be less than or equal to `comparative`
- `gt`: `Argument value` must be greater than `comparative`
- `ge`: `Argument value` must be greater than or equal to `comparative`
- `eq`: `Argument value` must equal to `comparative`
- `neq`: `Argument value` must NOT be equal to `comparative`
Note
- `eq` and `neq` are implicit number comparators and not to be mistaken by a strict left must equal right operator, just like `lt, le, gt, ge` (for example, comparing `1 > list object` would have no sense)
- If beneficial for performance or complexity the implicit type conversions can be removed and distinct operators introduced that do not have implicit type conversions
#### `contains_all, contains_none`
Stateless assert, for `list` type arguments.
- `contains_all`: The `argument value` must contain all items specified by `data`, but can contain more
- `contains_none`: The `argument value` must NOT contain any of the items specified by `data`, but can contain others
#### `limit`
Stateful assert, only `int` type arguments. When the authority is created, `interval_began` is set to `valid_from` from its custom active authority and `max_cumsum` to `0`. Incoming operations are first tried to match all stateless asserts,
and if all passes continue with stateful asserts. If `now > interval_began + interval_in_sec`, then set `max_cumsum = 0` and set `interval_began = now`.
The assert that needs to pass is now `current_cumsum + incoming value <= max_cumsum`. If all `asserts` of this `custom_active_authority` pass, update `current_cumsum = current_cumsum + incoming value`.
#### `limit_monthly`
Stateful assert, only `int` type arguments. Analogue to `limit`, but `interval_began` is initially set to `month(valid_from)` and set to `month(now)` on update, additionally the time assert is `month(now) >= interval_began + interval_in_months` (include logic for month overflow when year changes). The `month(now)` call assumes zulu time to calculate month number.
#### `attribute_assert`
Stateless assert, only for dictionary type objects. The data list contains restrictions that all must pass, the reference for the `argument` of the child restriction is nested into the attributes of the parent dictionary type object. Allows nesting of `attribute_assert`.
#### `logical_or`
Stateless assert, only for dictionary type objects. The data is a list of restrictions lists, i.e.
`data = [ [restriction 1, restriction 2], [restriction 3, restriction 4], ... ]`. If one of the restrictions sub-lists in data passes as whole, this restriction passes. In above miniexample that would mean if `restriction 1` and `restriction 2` pass, the whole `logical_or` restriction is considered to be passed as well.
### Outline of handling incoming transactions
When a signed transaction arrives and before the backend evaluates if all necessary authorities are present through the signatures, do the following:
- iterate over `required accounts`
- iterate over all `operations` (child operations of proposal are not included) within the transactions that require the active authority of this account
- iterate the `custom_active_authorities` of this account, and if it matches, remember that and continue with next `operation`
- if a `custom active authority` match was found for every operation in the loop, behave as if the `active authority` of this account is present for the corresponding operations.
Note:
- A `custom_active_authority` can only grant the `active authority` of the required account of the corresponding operation, nothing more
- The actual active authority of a required account can still be given as before, existing behavior is not to be changed
- This for illustration, not actual implementation instructions
### Modification to the backend
* Add a new index or extend the account object to store custom active permission are assigned to an account and contain a list of custom active authorities. Multiple custom active authority entries are possible for one operation
* Provide operations: `install_custom_active_authority`, `update_custom_active_authority`, `delete_custom_active_authority` to allow changing the custom active permission (3 operation to allow custom transaction fees and avoid having to send the complete list of all authorities for every update)
* If the active authority of the account is updated, all custom active authorities are disabled and must be manually specified / re-enabled. User can either
1. keep the authorities enabled by specifying them in a list of `custom_active_authorities` in `extensions` of `account_update_operation`
2. enable them again afterwards by using `update_custom_active_authority`
* Operation-specific authorities (if present) must be evaluated in incoming transactions
* Remove expired custom_active_authorities on maintenance if they are expired for longer than one month
* Additional committee parameters may be needed to limit the extend of usage of this feature
Notes: The implementation must not differentiate on which operation the custom active authority is applied, all operations are treated in same fashion
### Milestone 4: Number of executions
If Milestone 4 is implemented, a `custom active authority` receives an additional field `remaining_executions` to
specify the allowed number of executions.
The user can choose to restrict the valid time period and/or the number of executions, but the number of executions can only
be unlimited (not set) if a time period is specified. A `custom active authority` then matches if the time period is
valid or not set, and `remaining_executions` is either not set or > 0. When a `custom active authority` successfully grants
the active authority for the corresponding operation and the whole transaction is executed, `remaining_executions` is
decreased by one. If it becomes zero, the `custom active authority` becomes disabled.
If the `custom active authority` does not get replenished by the user within one month, it will be deleted.
# Economics
Adding a custom active authority means increased effort for the backend, and with a stateful one also the need for more storage. Proposed transaction fees:
- `install_custom_active_authority`: Normal accounts can only create custom active authoritites with a duration of maximum 1 year, LTM can do any duration. Two options come to mind:
- A fixed high fee independent of authorities content
- Tied to the duration and complexity of the custom active authority. Transaction fee is then `fee = flat_fee + basic_fee * duration` where `basic_fee` is calculated according to complexity (e.g. size of authority, number of restrictions and etc.). The period `duration` refers to the time that is still left, not the set duration
(i.e. `date_to - max(now, date_from)`)
- `update_custom_active_authority`: Base fee similar to `account_update` plus dynamic one for any duration increase, no payback if duration in decreased (increase/decrease is evaluated on both interval ends separately)
- `delete_custom_active_authority`: Cheap similar to `limit_order_cancel`
This logic forces the user to think about the desired duration and enforces to put it rather too short than too long.
If a custom active is expired, or considered to be too short, extending it is easily doable.
After expired, the custom active becomes disabled and can still be enabled again with a new period, paying the fee for that new period.
Note:
- For Milestone 4 the install fee would be dependent on the number of executions if no time period is set.
# Discussion
To be found in the [issue](https://github.com/bitshares/bitshares-core/issues/1061) and [pull request](https://github.com/bitshares/bsips/pull/86).
# Examples
These examples are for illustration and no specification of actual serialization.
#### Example: Nested arguments like `options`
Assume `asset_update_operation`. All attributes of its `options` must be filled on update call. This assert can not be used to realize a "may only change attribute xzy of `options`". This would require that the logic knows which of the arguments are reflected on-chain and it knows how to query it for every operation that contains `options`. If `options` are to be restricted with this assert, all values that should not change would need be fixated by defining an `any` assert for those attributes, while having e.g. a `lt` assert for the one attribute that is allowed to change.
#### Example: Simple transfer
Assume account A and B and some unrelated key K.
The custom active authority should be put such that a transfer transaction sending funds away from A can be signed with key K, as long as the receiver is B. More concrete, the authority would look like
```
custom active authority = {
valid_from: 7.7.2018 00:00
valid_to: 8.7.2018 00:00
operation_id: transfer,
authority: {
threshold: 1
key_auth: [key K, 1]
account_auth: []
},
restrictions: [
{
function: any,
argument: to,
data: [account B]
} // this restricts the argument identified with "to"
]
}
```
Exemplatory outcomes:
- Transfer asset X with amount Y from account A to account B, signed with Key K: Accepted
- Transfer asset X with amount Y from account B to account A, signed with Key K: Denied
- Transfer asset X with amount Y from account A to account C, signed with Key K: Denied
- Transfer asset X with amount Y from account A to account B, signed with active authority of B: Denied
- Transfer asset X with amount Y from account A to account B, signed with active authority of A: Accepted
- Create a proposal that includes operation 'transfer asset X with amount Y from account A to account B, signed with Key K: Accepted. Anyone can create a proposal.
Note:
- This is included with the first Milestone
- Normal permission logic is not altered. Account A can still sign the a transfer from account A to account B with its active authority
#### Involving multi-sig
Account A has multi-sig active authority of account B and C. Account A has a custom active authority that grants key K transfer priviliges (any asset to any account). Account B has a custom active authority that grants key L transfer priviliges (any asset to any account).
The transaction contains a transfer from A to account D. Required active authority of this operation is A.
- Signed by B and C: Accepted
- Signed by L and C: Denied. The custom active authority of B does not match, only applies for transfers with B as sender
- Signed by K: Accepted, basically bypassing multisig. This is intended, as the multisig needs to approve the installment of the custom active authority in the first place
#### Recursive active authority
Suppose Alice has a custom active authority with key K for transfers to Charlie. Bob has Alice as his active authority account. Suppose a transaction containing two operations
1. transfer 1 BTS from Alice to Charlie
2. transfer 1000 BTS from Bob to some other account
Cases:
- Transaction is signed by K
- Operation 1. requires Alice as active authority, and there is a matching custom active authority, thus this operation would be allowed to execute
- Operation 2. requires Bob as active authority. Even though Bob has Alice as active authority, K can NOT grant recursively the active authority of Bob
- The whole transaction is denied
- Transaction is signed by K and A
- Operation 1. requires Alice as active authority and is also directly present, is allowed
- Operation 2. requires Bob as active authority, which is indirectly present through A, execution is allowed (existing logic)
- The whole transaction is denied because too many signatures are present (existing logic)
- Transaction is signed by K and B
- Operation 1. requires Alice as active authority, and there is a matching custom active authority, thus this operation would be allowed to execute
- Operation 2. requires Bob as active authority and is also directly present, is allowed
- Transaction may execute
#### Example: Either or
Assume account A, B and C and asset X and asset Y. The custom active authority should now achieve
that a transfer transaction sending funds away from A can be signed with with active authority of account B if
- it sends less than 10000 of asset X to account C
- it sends less than or equal to 20000 of asset Y to account C
More concrete, the authority would look like
```
custom active authority = {
valid_from: 7.7.2018 00:00
valid_to: 8.7.2018 00:00
operation_id: transfer,
authority: {
threshold: 1
key_auth: []
account_auth: [account B, 1]
},
restrictions: [
{
function: logical_or,
data: [ either_list, or_list ]
}
]
}
either_list =
[
{
function: attribute_assert,
argument: amount,
data: [
{
function: lt,
argument: amount,
data: 10000
},
{
function: any,
argument: asset_id,
data: [ asset X ]
}
]
},
{
function: any,
argument: to,
data: [ account C ]
}
]
or_list =
[
{
function: attribute_assert,
argument: amount,
data: [
{
function: le,
argument: amount,
data: 20000
},
{
function: any,
argument: asset_id,
data: [ asset Y ]
}
]
},
{
function: any,
argument: to,
data: [ account C ]
}
]
```
Note: This is included with the third Milestone
#### Example: Checking for custom active authorities
Assume Account A, B and C. Now A has two `custom active authorities`:
- `custom active authority 1`: Allow Account B to transfer asset X to D
- `custom active authority 2`: Allow Account C to transfer asset X to D
The incoming transaction now contains `transfer 100 asset X from A to D, signed by all signatures required for active authority of C`.
The required accounts (meaning required active authority) for the transaction is Account A.
Backend would start considering `custom active authority 1` and check if active authority of account B is present through signatures.
It is not, thus continue by checking if authority of `custom active authority 2` is present, which it is.
Behave as if active authority of Account A is present for the matched operation and continue with normal authority checks.
Since the required accounts is Account A, and the given accounts is also Account A through `custom active authority 2`,
the transaction is executed.
# Milestones
We propose do split the implentation into multiple milestones. Each milestone will be voted on separately:
1. Implementation of basic functionaliy to allow custom active permissions and authorities, including `any`, `none` and `lt, le, gt, ge, eq, neq`, `contains_all, contains_none` and `attribute_assert` `asserts`. If deemed necessary by developpers, reduce to only allow one key or one account for every `custom active authority`
2. Implement stateful asserts `limit` and `limit_monthly`
3. Implement `logical_or`
4. Implement `remaining_executions`
# Summary for Shareholders
Bad publicity in terms of security can have very negative effect on the BTS value. This BSIP allows that traders can e.g. use a trading key, witnesses can use their witness key and a faucet can use a faucet key. If then for some reason the key or witness/faucet server becomes compromised, such a key can do little harm to the account holders, minimizing the risk.
This BSIP opens up a lot of use-cases as presented in Motivation section. The intention is to not alter any existing logic of the permission system, which reduces the risk of malfunctioning.
# Copyright
This document is placed in the public domain.

View file

@ -1,186 +0,0 @@
BSIP: 0042
Title: Adjust price feed to influence trading price of SmartCoins
Author: Abit More <https://github.com/abitmore>
Status: Up for voting
Type: Protocol
Created: 2018-08-22
Workers: 1.14.118 (pro), 1.14.119 (con)
# Abstract
We here propose to dynamically adjust price feed in order to influence trading
price of smart coins to achieve tighter peg.
This BSIP is constantly evaluated in terms of being accepted or rejected,see the last section *Constant voting evaluation* for details.
# Motivation
To get mass adoption, it's better that the SmartCoins can peg to targets more
tightly. E.G. bitUSD pegs more tightly to Fiat USD.
# Rationale
When BTS is in a downtrend, the SmartCoins are always being traded at a
premium; when BTS is in a uptrend, the SmartCoins tend to be traded with a
discount. Here is a chart showing historical trading price of bitUSD:
https://coinmarketcap.com/currencies/bitusd/
Typically a premium is around 10%, and a discount is around 5%. Although some
people think the numbers are not very large, other people think they're too
large. In this BSIP we aim to reduce the numbers.
Trading price of a SmartCoin is influenced by
* underlying value guaranteed by collateral;
* demand vs supply.
## Downtrend and premium
When BTS is in a downtrend, before a black swan event, supplies of SmartCoins
are squeezed, while the underlying value is still guaranteed if price feeds are
around real trading price, thus trading price of the SmartCoins will be pushed
up.
If we slightly adjust the price feed, thus slightly loose the guarantee on the
underlying value, hopefully we can push the trading price of SmartCoins towards
par. Since adjusting price feed affects supply as well, ideally we don't need to
adjust much to achieve the goal.
Other options include decreasing MCR to stimulate supply, or decreasing MSSR to
suppress demand.
### Negative feedback
Actually we don't know what's the best offset to be applied to the inputs, but
we can adopt a negative feedback approach. When adjusting the inputs, keep an
eye on the result (trading price of SmartCoins). If the adjustment is in the
correct direction, the price should move towards par. If the price moved too
little, we adjust more; if the price moved too much, we adjust less. Finally
this will lead to a stable result.
We may consider setting a hard limit on the offset which may make us feel safer.
Actually, to be safe, we do need to start with a small offset, and adjust little
by little. Since it's expected that the best offset will be figured out by the
negative feedback mechanism, a preset limit may impact the mechanism negatively.
A few witnesses publishing too far away offset doesn't harm much because
they won't move the median much. In addition, stake holders may vote down
perceived bad actors.
### Risks
All the adjustments (price feed, or MCR, or MSSR) in a downtrend actually looses
requirement of collateral ratio, so it seems it will increase the possibility
of black swan events. This is actually the most contraversial part of this BSIP.
The counter argument is about liquidity. As we can see, even without the
adjustments, black swan events have occurred on bitHKD, bitSGD and some other
SmartCoins due to poor liquidity. In contrast, bitCNY, bitUSD and etc have
survived due to good liquidity. With the adjustments, hopefully we'll have
better adoption, which means better liquidity in the markets, so possibility
of black swan events would likely decrease.
### Guarantee of value
Adjusting price feeds impacts force settlements. Specifically, a user will
likely get less by force settling when the price feed is adjusted. This lead
to an argument says it breaks guarantee of SmartCoins' value.
The counter argument is also liquidity. With good liquidity, users should buy
from market rather than force settling. It's up to UI to guide users for better
experience. If a user has a large volume to trade, she has to be patient,
since even go the force settlement approach she will likely encounter the
volume limitation as well.
### Margin call price
Actual price (in FIAT) when buying into a margin call would be unchanged,
because the adjustment will shift trading price of SmartCoins but not BTS.
It's expected that margin calls will be less though.
### User experience changes
Currently, GUI shows median price feed on the market page. By looking at the
price,
people know what price BTS is trading around. Then people can check lastest
trading price of BTS / SmartCoin pairs, to know how much premium or discount
that the SmartCoins are trading at.
After applied the adjustments on price feeds, the median price feed showing
on market page of GUI will no longer mean trading price of BTS, instead, it
will mean a somewhat "guiding price" for SmartCoin production. People may get
confused especially in the beginning of applying the adjustments.
On the other hand, after applied the adjustments, hopefully SmartCoins will
be traded on par, so latest trading price of BTS / SmartCoin pairs will
indicate trading price of BTS.
It's up to the GUI development team to optimize the GUI for better user
experience.
## Uptrend and discount
When BTS is in a uptrend, usually SmartCoins are oversupplied which results in
devaluation. Ideally, to reduce supply, the best approach is to increase MCR.
However, at this moment, there is a bug in BitShare-Core so we can't adjust MCR
freely (more info is here:
https://github.com/bitshares/bitshares-core/issues/1270). Before the bug is
fixed, we can adjust price feed instead, similar to downtrend, with negative
feedbacks, but in opposite direction.
Note: when adjusting price feed in a uptrend, we should set a fair force
settlement offset at same time, see [BSIP 16](bsip-0016.md) for more info.
# Specification
When witness publishing a price feed, after got price of BTS from exchanges
(assuming it's `P`), check trading price of the publishing SmartCoin,
adjust `P` with an algorithm.
To be safe, the algorithm should start with a small offset, or a value near
the median, and adjust the offset little by little.
The algorithm should implement negative feedback,
that said, it should track historical adjustments and historical differences
on trading prices of SmartCoins, and make new adjustments accordingly.
We don't force all witnesses to use a same algorithm, instead, witnesses are
encouraged to implement different algorithms for same goal.
We also don't set a hard limit about how much the offset should be within, in
order to let the negative feed back mechasim find the best result by itself.
Witnesses should make their own decisions on whether to set a hard limit and
how much should it be if need to set one, generally, to reduce impacts caused
by bugs.
It will be good to apply the change to bitCNY first, which has much better liquidity
than other smartcoins. After witnesses and community learned enough in the process
it can be also applied to bitUSD.
# Discussion
- https://bitsharestalk.org/index.php?topic=26948.0
- https://bitsharestalk.org/index.php?topic=26315.0
- https://bitsharestalk.org/index.php?topic=26966.0
# Summary for Shareholders
The peg of SmartCoin to the underlying asset is crucial to create trust for SmartCoin holders, in combination with a force settlement offset that is considered fair. This BSIP seeks to adress the issue of volatility with respect to the peg by allowing the witnesses to implement (within boundaries) their own price feed strategy that is targeted to uphold the peg and provide a fair force settlement offset.
This is a crucial intrusion into the open market mechanics and is thus not a strict directive to the witnesses, furthermore this BSIP is constantly evaluated, and if it becomes rejected (see the next section), witnesses are bound to return to the former price feed mechanisms.
# Constant voting evaluation
This BSIP has a pro and a con worker and has an ever evaluated state of accepted and rejected.
- **Accepted**:
The pro worker is active in terms of receiving payout from the reserve pool AND its votes surpass the con worker.
- **Rejected**:
The pro worker is NOT active (is not receiving funds from reserve pool) OR the votes of the con worker surpass the pro worker. If the pro worker expires, this BSIP is also considered rejected.
The earliest that this worker can become active is 7th September 2018.
# Copyright
This document is placed in the public domain.

View file

@ -1,292 +0,0 @@
BSIP: 0044\
Title: Hashed Time-Locked Contract\
Authors: Ryan R. Fox, John M. Jones, taconator\
Status: Draft\
Type: Protocol\
Created: 2018-08-22\
Discussion: https://github.com/bitshares/bsips/pull/104
# **Abstract**
This BSIP describes an implementation of a Hashed Time-Locked Contract (HTLC) operation.
# **Motivation**
The ability to securely hold tokenized assets within a hashed time-locked contract on the BitShares blockchain is a desirable feature that could be used by many persons, services, and businesses to mitigate risks between participants during asset transfer. HTLC implement conditional transfers, whereby a designated party (the "recipient") will reveal the preimage of a hash in order to execute the asset transfers from a second party (the "depositor"), else after time lock expiry "depositor" may retrieve their assets. No third-party escrow agent is required, rather the HTLC operation enforces conditions, evaluations and transfers through the BitShares consensus protocol.
# **Rational**
## **Elements of a Hashed Time-Locked Contract (HTLC)**
An HTLC is defined to have the following components:
* Parties to the HTLC
* The depositor
* The recipient
* Secured Asset
* Symbol
* Quantity
* Conditions
* Hash lock
* Preimage (the secret)
* Preimage hash (hash of the preimage)
* Preimage length
* Time lock
* Timeout threshold (expiry)
* Condition Evaluators
* Fees
* Prepare operation fee
* Prepare duration fee
* Redeem operation fee
### **Parties**
Two parties must be defined within each HTLC: the `depositor` and the `recipient`. The `depositor` will secure their assets within the HTLC and designate the `recipient` to receive them. Note that a proposal transaction may be used for tasks such as multi-signature, but the end result at approval remains a single `depositor` and a single `recipient`.
### **Secured Asset**
An HTLC involves a conditional transfer of the defined `asset symbol` in the amount of `assets quantity` from the `depositor` to the `recipient`. The HTLC holds these designated `secured assets` from `depositor` on the blockchain and will continue to enforce the specified `conditions` until one is satisfied.
### **Conditions**
There are two competing conditions within an HTLC, the `hash lock` and the `time lock`.
The HTLC contains a `hash lock` condition, which comprise both the `preimage hash` and `preimage length`, barring the transfer of held `secured assets` unless satisfied. If a `preimage` of requisite `length` is provided to the HTLC which generates a hash matching the `preimage hash`, the `preimage` is then stored within the blockchain, and the `secured assets` are transferred to the `recipient`.
If a satisfactory `preimage` is not provided to the HTLC before the stipulated `time lock` expires, the `depositor` may request the return of `secured assets`. The HTLC will only evaluate transfer request from `depositor` and after `timeout threshold`, then return `secured assets` to `depositor`.
**Note:** we recommend the Committee the set maximum allowable `preimage length` to ensure unreasonably large submissions are rejected.
### **Condition Evaluators**
The `preimage` can be thought of a secret key, that will eventually be shared with the `recipient`. This can be a word, a phrase, or even a random series of bytes. The `length` of the `preimage` must be specified within the HTLC at creation.
Upon presentation of a `preimage`, the HTLC `condition evaluator` validates:
1. That the `timeout threshold` has not yet occurred.
2. That the length of the `preimage` matches the specified `preimage length`.
3. That the hash of the `preimage` calculates to the specified `preimage hash`.
If all evaluations succeed, the `secured assets` are transferred to the `recipient`. If any evaluation fails, nothing happens; the HTLC remains ready to evaluate the next `preimage`.
### **Timing of Condition Evaluation**
The `timeout threshold` of the contract is defined by `depositor` within the HTLC at creation. It can be any time in the future and should allow enough time for `recipient` to review the HTLC and provide the `preimage`. Further, it should not be set too far into the future to mitigate against an unresponsive `recipient` impacting `depositor`, as their `secured assets` will be locked until `timeout threshold` expiry. The accuracy is based on when the `condition evaluator` runs, and should be considered accurate ± 15 seconds.
**Note:** we recommend the Committee set the maximum value for `timeout threshold` to limit the amount of time a contract may consume memory of validation nodes.
### **Early Termination of an HTLC**
To protect the `recipient`, early termination of an HTLC is not allowed by any party. Placing a `timeout threshold` far into the future is valid, up to the maximum defined by the Committee. User protection from locking up funds for an extremely long period could be provided by the UI used to create the HTLC.
### **Automatic Transfers Upon Expiry**
Upon expiry of the `timeout threshold`, the `secured assets` held within the HTLC will be queued for return to `depositor`. From this time, the HTLC will no longer evaluate the `hash lock`, preventing `recipient` from receiving the `secured assets`. No action is required by the `depositor` to receive their "locked" funds back from the contract after expiry.
### **Fees**
We propose three (3) operations (see Specification) to implement the HTLC feature, each requiring distinct fees. All fees will be set and maintained by the Committee.
The "prepare" operation will store in-memory data on validation nodes until redeemed or expiry. We recommend the `htlc_preparation_fee` be comprised of two (2) components: `GRAPHENE_HTLC_PREPARE_FEE` which is flat and `GRAPHENE_HTLC_DAILY_FEE` which is variable based on the number of days until `timeout threshold`.
The "redeem" operation frees most of the memory from the validation nodes and adds the `preimage` data into blockchain storage when the transaction is validated. We recommend the `htlc_redemption_fee` be comprised of two (2) components: `GRAPHEN_HTLC_REDEEM_FEE` which is may be quite low and `GRAPHENE_HTLC_KB_FEE` which is variable based on the total number of kilobytes of data committed to the blockchain.
The "extend expiry" operation will update the `timeout_threshold` to a future date, extending in-memory resources on validation nodes. We recommend the `htlc_extend_expiry_fee` be comprised of two (2) components: `GRAPHENE_HTLC_EXTEND_EXPIRY_FEE` which is flat and `GRAPHENE_HTLC_DAILY_FEE` which is variable based on the number of additional days added to extend the `timeout_threshold` of the contract.
## **Existing Escrow Proposals**
This section describes various escrow concepts that have been proposed either for BitShares or for other blockchains or services in terms of the elements that have been defined above. This is intended to provide some background and comparison to the concepts that follow.
### **BitShares Escrow**
A separate BSIP [cite] is currently being discussed that provides a more traditional escrow service. This involves parties, agents, and a more complex evaluation. HTLC shares some similarities, and could be considered a thin subset of BitShares Escrow.
The smaller, well-defined nature of HTLC provides a major advantage for applications that want to attempt tasks such as cross chain atomic swaps.
### **Scorum Atomic Swap**
[cite]
### **BitShares Multi-Signature Account**
One of the existing features of BitShares is the ability to have an account that requires multiples signatures by differently authorized parties [cite] and even hierarchical authorizations. Using this mechanism as a form of escrow is possible. But there are many limitations. More information on escrow and multi-signatures can be found in the BitShares Escrow BSIP [cite].
### **BitShares Proposals**
One of the existing features of BitShares is the ability to have a proposal that is recorded on the blockchain and awaits the authorization of the requisite parties (e.g. M-of-N signatures) to execute. However, the proposal does not "lock" any assets, so the transfer will fail if the sending account lacks sufficient funds during validation. If the required authorizations are not given by proposal expiry, then no transfer will occur. This feature also contains many limitations when compared to HTLC.
## **Possible Concepts to Implement**
The following will describe possible concepts that could be implemented within the BitShares protocol.
### **Set-Price Swap**
Two parties may agree on a swap of two distinct `secured assets` at a set price (defined exchange ratio), without using an exchange such as the BitShares DEX. This will require two (2) HTLC contracts containing the identical `preimage hash` within each to "link" them together and facilitate the execution of an "atomic swap" of these "locked" `secured assets` between the party's accounts resulting in a trustless value exchange.
#### **Business Approach**
Alice begins by generating a distinct `preimage` of her choosing, notes the `preimage length` and calculates the `preimage hash`. She retains the `preimage` in secret, then creates a new HTLC stipulating that the `depositor` account "alice" will transfer `quantity` "100" "bitUSD" `asset` into the `recipient` account "bob" if a `preimage` is presented matching the `preimage hash` before the `timelock threshold` of 10AM tomorrow. Upon consensus validation of the HTLC, the 100 bitUSD `secured assets` are transferred from Alice's `depositor` account into the HTLC where they remain locked by the `preimage hash` and `timelock threshold`. She then shares the resulting `contract identifier` with Bob.
Bob queries the blockchain for the `contract identifier` Alice provided. He examines to ensure it contains his desired `recipient` account, `asset` symbol, asset `quantity`, `preimage length`, and `timelock threshold`. Bob now creates his own HTLC that will deposit `quantity` "10,000" "BTS" `symbol` into the `recipient` account "alice" from `depositor` account "bob", if a `preimage` that generates the `preimage hash` Bob copied from Alice's HTLC before the `timelock threshold` of 5pm today. Upon consensus validation of Bob's HTLC, his 10,000 BTS `secured assets` are transferred from his `depositor` account and "locked" into the contract. He then shares the resulting `contract identifier` with Alice. Notice Bob specified a `timelock threshold` much shorter than Alice defined in her contract. This ensures Bob will have enough time to observe and use the `preimage` Alice will publish to the blockchain next.
Alice now examines the HTLC Bob created, ensuring the `preimage hash` and `preimage length` both match the original values she used within her contract. She also verifies her desired `recipient` account "alice", the `quantity`, `symbol`, and the `timelock threshold` agree with her intentions. She now uses her `preimage` to "unlock" Bob's contract. Once consensus validation occurs, the HTLC will transfer the `secured assets` 10,000 BTS into her `recipient` account "alice". This reveals the `preimage` on the BitShares blockchain for Bob to use next. NOTE: She must do this before 5PM. Otherwise, Bob may (and should) reclaim the funds in the contract he created.
Bob can now observe the `preimage` Alice used to "unlock" his HTLC, and he will use it to "unlock" her HTLC to receive the 100 bitUSD `secured assets` into his `recipient` account "bob". NOTE: He must do this before 10AM tomorrow. Otherwise, Alice may (and should) reclaim the funds in the contract she created.
### **Cross-Chain Swap**
Similar to the set-price swap mentioned above, two parties may exchange tokens between distinct blockchains when both implement HTLC support. Bitcoin, Litecoin and many others support HTLC [cite].
#### **Business Approach**
Alice and Bob intend to swap BTC (bitcoin token) and BTS (BitShares token). This will require both parties to define both a BTC deposit address and BTS deposit account. These addresses/accounts will be exchanged between the parties.
Alice will initiate the first leg of the swap on the BitShares Network with her HTLC and Bob will follow up on the Bitcoin Network with his HTLC. Allice generates a distinct `preimage` of her choosing, notes the `preimage length` and calculates the `preimage hash`. She retains the `preimage` in secret, then creates a new HTLC stipulating that the `depositor` account "alice" will transfer `quantity` "10,000" "bitUSD" `asset` into the `recipient` account "bob" if a `preimage` is presented matching the `preimage hash` before the `timelock threshold` of 10AM tomorrow. Upon consensus validation of the HTLC on the BitShares Network, the 10,000 bitUSD `secured assets` are transferred from Alice's `depositor` account into the HTLC where they remain locked by the `preimage hash` and `timelock threshold`. She then shares the resulting `contract identifier` with Bob.
Bob queries the BitShares Network for the `contract identifier` Alice provided. He examines to ensure it contains his desired `recipient` account, `asset` symbol, asset `quantity`, `preimage length`, and `timelock threshold`. Bob now creates and funds his own HTLC on the Bitcoin Network that will spend the `UTXO` of this contract to the `recipient address` Alice provided during their setup phase, of `amount` 1 BTC if a `preimage` that generates the `preimage hash` Bob copied from Alice's HTLC before the `timelock threshold` of 5pm today. Upon consensus validation of Bob's HTLC on the Bitcoin Network, 1 BTC he controlled are spent into the contract and "locked". He then shares the resulting `contract identifier` with Alice. Notice Bob specified a `timelock threshold` much shorter than Alice defined in her contract. This ensures Bob will have enough time to observe and use the `preimage` Alice will publish to the blockchain next.
Alice now examines the HTLC Bob created on the Bitcoin Network, ensuring the `preimage hash` and `preimage length` both match the original values she used within her contract. She also verifies her desired `recipient address`, `quantity`, and `timelock threshold` agree with her intentions. She now uses her `preimage` to "unlock" Bob's contract. Once consensus validation occurs on the Bitcoin Network, the HTLC will spend 1 BTC to Alice's `recipient address`. This reveals the `preimage` on the Bitcoin Network for Bob to use next. NOTE: She must do this before 5PM. Otherwise, Bob may (and should) reclaim the funds in the contract he created.
Bob has now observed the `preimage` Alice used to "unlock" his HTLC, and he will use it to "unlock" her HTLC to receive the 10,000 bitUSD `secured assets` into his `recipient` account "bob". NOTE: He must do this before 10AM tomorrow. Otherwise, Alice may (and should) reclaim the funds in the contract she created.
# **Specifications**
## **Objects**
```
class htlc_object : public graphene::db::abstract_object<htlc_object> {
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_htlc_object_type;
account_id_type depositor;
account_id_type recipient;
asset amount;
fc::time_point_sec expiration;
asset pending_fee;
vector<unsigned char> preimage_hash;
uint16_t preimage_size;
transaction_id_type preimage_tx_id;
};
```
## **Operations**
### **Prepare**
```
transaction_obj htlc_prepare(depositor, quantity, symbol, recipient, hash_algorithm, preimage_hash, preimage_length, timeout_threshold, htlc_preparation_fee)
Validate: HTLC signed by requisite `authority` for `depositor` account
Validate: `depositor` account has requisite `quantity` of `symbol` asset for the `guarantee`
Validate: `timeout_threshold` < now() + GRAPHENE_HTLC_MAXIMUM_DURRATION
Calculate: `required_fee` = GRAPHENE_HTLC_OPERATION_FEE + GRAPHENE_HTLC_DAILY_FEE * count((`timeout_threshold` - now()), days)
Validate: `depositor` account has requisite `quantity` of BTS for `required_fee`
Validate: `recipient` account exists
Validate: `preimage_length` does not exceed GRAPHENE_HTLC_MAXIMUM_PREIMAGE_LENGTH
Validate: `preimage_hash` well formed
Update: BTS balance of `depositor` based on `required_fee`)
contract = new htlc_obj
Set: `contract.depositor` = `depositor`
Set: `contract.recipient` = `recipient`
Set: `contract.hash_algorithm` = `hash_algorithm`
Set: `contract.preimage_hash` = `preimage_hash`
Set: `contract.preimage_length` = `preimage_length`
Set: `contract.timeout_treshold` = `timeout_threshold`
Transfer: from `depositor` account to `contract.quantity` of `contract.symbol`
return results
```
### **Redeem**
```
transaction_obj htlc_redeem(fee_paying_account, id, preimage, htlc_redemption_fee)
Validate: transaction signed by requisite `authority` for `fee_paying_account` // any account may attempt to redeem
Get: get_htlc(id)
Validate: `fee_paying_account` account has requisite `quantity` of BTS for `htlc_redeem_fee` and `htlc_kb_fee`
Update: balance of `fee_paying_account` based on total fees
// Evaluate: timelock
if now() < `timeout_threshold` then return error // "timeout exceeded"
// Evaluate: hashlock
if length(preimage) != `id.preimage_length` then return error // "preimage length mismatch"
Calculate: `preimage_hash` = hash(preimage)
if `preimage_hash` != `id.preimage_hash` then return error // "invalid preimage submitted"
Update: balance of `id.recipient` add asset `id.symbol` of quantity `id.quantity`
Add: transaction to mempool
Set: `id.preimage_tx_id` = `transaction_id`
Cleanup: memory allocated to this htlc
Virtual Operation: Update account history for `depositor` to reflect redemption as by default the above operation will only appear for `redeemer`
return: results
```
### **Extend Expiry**
```
transaction_obj htlc_extend_expiry(depositor, id, timeout_threshold, htlc_extention_fee)
Validate: 'depositor' = get_htlc(id).depositor
Validate: `timeout_threshold` < now() + GRAPHENE_HTLC_MAXIMUM_DURRATION
Calculate: `required_fee` = GRAPHENE_HTLC_DAILY_FEE * count((`timeout_threshold` - now()), days)
Validate: `depositor` account has requisite `quantity` of BTS for `required_fee`
Update: BTS balance of `depositor` based on `required_fee`)
Set: `contract.timeout_treshold` = `timeout_threshold`
return results
```
### **At Expiry** (evaluated at each block commit)
```
Get: get_htlc(id)
Update: balance of `depositor` add asset `id.symbol` of quantity `id.quantity`
Cleanup: memory allocated to this htlc
Virtual Operation: Update account history for `depositor` to reflect expiry without redemption.
```
## **cli_wallet APIs**
### **htlc_prepare**
### **htlc_redeem**
### **htlc_extend_expiry**
## **witness_node APIs**
### **get_htlc**
### **get_htlcs_for_account**
# **Discussion**
https://github.com/bitshares/bsips/pull/104
# **Summary for Tokenholders**
Hashed Timelock Contracts (HTLCs) enable conditional transfers, whereby distinct account holders may transfer tokens from one account (`sender`) to a second account (`receiver`) before a defined expiry (`timelock`), only if the `preimage` (a.k.a. password) is revealed (`hashlock`) on the blockchain. If the `hashlock` condition is not satisfied prior to the `timelock` the tokens are return to the `sender`.
A typical scenario involves “Alice” and “Bob” each having accounts on the BitShares Network and addresses on the Bitcoin Network willing to trade their tokens. Alice will begin by creating an HTLC on BitShares to transfer BTS tokens from account `alice` to account `bob` with conditions set for hash of preimage (`hashlock`) and contract expiry (`timelock`). Bob will review her HTLC, if acceptable he will create an HTLC on the Bitcoin Network to transfer BTC from `his address` to `her address` with conditions set to the same `hashlock` value and a `timelock` value approximately half that specified by Alice. Next, Alice will review Bobs HTLC for correctness and if acceptable, will redeem the BTC therein by publishing her `preimage` to satisfy the `hashlock` prior to the `timelock` expiry. Finally, Bob will observe the revealed `preimage` and use it to redeem Alices HTLC on the BitShares Network resulting in the BTS transferring to his account. Alice and Bob successfully exchanged native BTS and BTC at their agreed to ratio without any intermediaries.
# **Copyright**
This document is placed in the public domain.
# **See Also**
A description of [Hashed Timelock Contracts](https://en.bitcoinwiki.org/wiki/Hashed_Timelock_Contracts)

View file

@ -1,85 +0,0 @@
```
BSIP: 45
Title: Introduce 'allow use as bitasset backing collateral' flag/permission to assets
Authors: @grctest
Status: Draft
Type: Protocol
Created: 07/10/2018
Discussion: https://github.com/bitshares/bsips/issues/80
Replaces: N/A
Superseded-By: N/A
Worker: N/A
```
---
# Abstract
It's currently possible to impose new asset settings through MPA encapsulation without the permission of the backing asset's 'asset owner'.
This BSIP proposes to introduce a new asset permission/flag which enables the asset owner to enable|prevent MPA encapsulation.
# Motivation
By encapsulating an asset (UIA/EBA|MPA) within a new MPA, you can impose new asset settings upon the underlying asset, to the possible detriment of the backing asset's 'asset owner'.
# Rational
By providing asset owners this functionality, we can improve asset owner confidence in the finality of their configured asset settings.
# Specifications
## Create new 'allow use as backing collateral' flag/permission
Rather than create a system of inheriting permissions from backing collateral, a new flag/permission for 'allow use as MPA backing collateral' could simply prevent MPA encapsulation entirely at the discretion of the asset owner.
Existing assets which are currently configured as an bitasset's backing collateral would require this flag to be set default enabled (allowed). This couldn't be changed unless the bitasset reconfigured to an alternative backing collateral - impossible if supply is greater than 0.
Non applicable assets (PM & twice nested MPA) would prevent the flag from being enabled.
Existing assets currently not used as backing collateral could be set to disabled by default.
# Discussion
## Consequences of MPA encapsulation
* Removal/Bypassing of market fees (if enabled)
* Re-implementation of confidential transfers (if disabled)
* Evasion of whitelist/blacklist (both user & market lists)
* Preventing the issuer from transfering the asset back to themselves (Can't transfer backing collateral back to yourself)
* Remove backing asset issuer from transfer approval provess.
## Committee configuration
Should all smartcoins be allowed as bitasset backing collateral? Given that XCD already does this with bitUSD, I think it's appropriate. That said, not all committee owned bitassets are in a stable state (bitGOLD for example is in global settlement state right now).
## Enabling the flag grants permisson for all
Currently you can perform MPA encapsulation without involving the asset owner, this could introduce conflict between the two asset owners.
If the flag is enabled, that's an indication that the asset owner accepts any bitasset use case - you wouldn't need to seek explicit permission prior to creating experimental bitassets on the BTS DEX.
If it's disabled, that's a clear indication that the asset owner doesn't want it used as backing collateral.
## How to configure assets held by null-account?
It's possible that bitassets may be owned by null-account but remain operational, configuring default disabled would burn the possibility of encapsulation - if these assets exist then if possible should be set to enabled?
## Proposed UI changes
This flag could only work as long as no MPA has already selected the asset as its backing collateral; setting this as default disabled (not allowed) for newly created assets in the asset creation form could help prevent the asset being used as backing collateral without the user's knowledge.
---
# Summary for Shareholders
* Introduces new asset owner permissions.
* Helps mitigate negative MPA encapsulation consequences, improving gateway regulatory compliance capability?
* Given enabled flags could constitute advanced permission for MPA use case, there may be UIA backed MPA created which would contribute BTS fees to the reserve pool.
# Copyright
This document is placed in the public domain.
# See Also
N/A

89
bsip-1200.md Normal file
View file

@ -0,0 +1,89 @@
BSIP: 1200 (unassigned)
Title: Stealth development, Phase II
Authors: Christopher J. Sanborn <...>
Agorise, Ltd. <Agorise@protonmail.ch>
Status: Draft
Type: Informational
Created: 2018-01-29
Discussion: <https://t.me/Agorise>
## Abstract
To discuss the continued development of Stealth functionality and provide an overview of the following BSIPs which define components of that development.
Component BSIPs: _(Works in progress!!)_
Number | Title | Type | Status
:-----------------:|--------------------------------------------------------------|---------------|--------
[1200](bsip-1200.md) | Stealth development, Phase II — _(this document)_ | Informational | Draft
[1201](bsip-1201.md) | New operations for Confidential Asset (CA) transactions | Protocol | Draft
[1202](bsip-1202.md) | Ring signatures for untraceability of Stealth transactions | Protocol | Draft
[1203](bsip-1203.md) | Blockchain scanning for inbound Stealth transactions | Protocol | Draft
[1204](bsip-1204.md) | Deterministic addresses for Stealth wallets | Informational | Draft
[1205](bsip-1205.md) | Metadata hiding via Garlic Routing and other means | Informational | Draft
## Motivation
The initial phase of Stealth development was proposed and implemented in [BSIP-0008](bsip-0008.md), and is live on the BitShares network. Support for this first round of confidentiality features has been implemented in the CLI wallet, and has also been demonstrated in the UI wallet by Agorise, Ltd., in a code fork not yet integrated into the mainline UI-Wallet code. Utilization of the privacy features remains low, for two reasons: (1) the difficulty of using the CLI wallet for day-to-day activities, and (2) the Stealth feature set thus far, while valuable, does not yet provide a comprehensive privacy solution.
Phase One of Stealth development consisted of the implementation of Confidential Transactions (CT) [[1]](#see-also), which was initially proposed for the Bitcoin network in a paper by Greg Maxwell. CT provides two key features: **value-blinding**, and **stealth addresses**. Value-blinding means that the value amounts of transactions are unknowable except to the parties of the transaction (provided the transaction is sufficiently removed from the operation that initially converted a public balance to a blind balance). Stealth addresses are an address format that the sender can use to derive a "shared secret" public key for which only the recipient can derive a private key, without revealing publicly that the stealth address and the public key used to transmit the funds are related. The use of stealth addresses helps to anonymize transactions, however it creates a burden of communication between the sender and the recipient, who must be made aware of the existence of an inbound transaction.
Stealth addresses also provide partial **unlinkability**, or the inability to "link" balance elements (we'll call them UTXOs for Unspent Transaction Outputs) together to see that they are controlled by the same party. However, wallet implementations may, in order to facilitate discovery by the receiving party, publicly embed the stealth address of the receiving party into the transaction, thus breaking unlinkability and threatening anonymity. Heretofore, no privacy-preserving method has been proposed on this network to enable discovery, other than the sender and receiver being in direct communication off of the blockchain (e.g. sending **transaction receipts**). Furthermore, CT transactions are **traceable**, meaning that a transaction reveals which UTXOs are consumed in the creation of new UTXOs. This has two implications: (1) a transaction history can be constructed, and it may be possible to establish a vary narrow set of originating users who initally "blinded" a previously public balance, thus potentially establishing to a high degree of probability *who* is involved and *how much* value is involved in a particular sequence of transactions, and (2) a user spending a balance consisting of more than one UTXO will of necessity reveal that those UTXOs are controlled by the same party, or "linked," thus again breaking unlinkability.
In what follows we propose methods of enhancing the confidential abilities offered by the BitShares network by integrating specific solutions to achieve unlinkability, untraceability, and automated transaction discovery by the receiving party. Additionally, since BitShares is a multi-asset blockchain, we propse to adopt Confidential Assets (CA). CA is an extension to CT that hides not just the values of a transaction, but also the assets involved. Further, we propose various convenience and user-experience enhancements to ease the backup burden placed on users and reduce the chances of lost funds. Lastly, we propose an ongoing effort to harden wallets and p2p nodes against metadata leaks.
## Rationale
We view "Stealth" as a constellation of features providing robust privacy and "grandma-friendly" usability and reliability. A user of Stealth transactions should be reasonably assured that their privacy is complete, and not underminable by easy-to-make procedural mistakes.
### "Blinded" vs. "Stealth"
To facilitate an orderly, confusion-free upgrade, and to differentiate between Phase One and Phase Two functionality, we have adopted the convention of referring to the existing CT transactions that only blind transaction amounts as **Blind Transfers**, and the proposed more fully-private transaction features as **Stealth Transfers**. The names convey that Stealth Transfers will be more private than Blind Transfers (although some user education will be needed on this). Upon maturity of the Stealth feature set, the utilization of Blind transfers should be retired.
### Specific features and enhancements
Specific features and enhancments proposed by this and associated BSIPs are as follows:
#### Asset Hiding
Confidential Assets (CA) [[2]](#see-also) extends Confidential Transactions (CT) to include asset hiding. Existing CT functionality can hide the value amount of a transaction, but the asset being transfered is publically visible in the transaction format. Since BitShares is a multi-asset blockchain, it would be of value to hide not just the value but also the identity of the asset involved. CA provides a method to do this. The proposal to implement CA on the BitShares network is in [BSIP-1201](bsip-1201.md).
#### Unlinkability and Untraceability
While BitShares is an account-based blockchain, similar e.g. to Ethereum and others, Stealth operations on the BitShares network follow a UTXO model, similar to BitCoin and related blockchains. UTXOs (Unspent Transaction Outputs) are discrete balances held in the "outputs" of transactions. A user's total balance is composed of the sum total of all UTXOs that fall under their control. A Stealth transaction consists of the destruction of one or more existing UTXOs and the creation of one or more new UTXOs. CT guarantees that the values of the outputs are unknowable (except for deductions that can be made if one happens to know, precisely or approximately, the values of the inputs). However, the current implementation of CT provides no privacy regarding *which* UTXOs are used as inputs to the transaction. Because of this, current CT transactions are fundamentally *traceable* and *linkable*. **Traceable** means that a history of prior inputs can be constructed, "tracing" where an output came from, and if the history is short enough (refering to how many prior UTXOs one must traverse before finding an operation where a public balance was converted to a blind balance) then it may be possible to reveal involved parties and estimate transaction values. **Linkability** refers to the ability to show that a set of UTXOs are controlled by the same party, or that a set of disparate transactions were conducted by the same party. Although the latter is well protected due to non-reuse of public keys, the former is implicated by CT. A CT transaction consuming multiple inputs necessarily reveals that all inputs are controlled by the same party, and if anonymity has been compromised for one input UTXO, then it is effectively compromised for all of them.
To solve the problems of linkability and traceability, we propose to take a page from the Monero project. The Monero network uses a system of **ring signatures** to create a high degree of plausible-deniability as regards who exectuted any particular transaction [[3]](#see-also). A ring signature is an *n* of *m* signature scheme wherein the set of inputs to a transaction is much larger than the set of inputs actually consumed by the transaction, and the signature provided guarantees that the correct party signed the transaction, but makes it impossible to know *which* party is the signer. With a Monero-like ring signature scheme, it is no longer possible to determine *which* UTXOs are "spent" vs. "unspent" (a mechanism to prevent double-spends does exist, of course). This means that it is no longer possible to construct an exclusive directed graph if inputs to outputs, thus providing untraceability and unlinkability. (More specifically, the set of inputs that *might* be in the history of a particular output rapidly becomes so large that it is no longer possible to say with significant probability that any particular party was involved.)
We propose and discuss the implementation of ring signatures for Stealth transactions in [BSIP-1202](bsip-1202.md).
#### Scanning for Inbound Stealth Transactions
The current implementation of CT requires that a sender must communicate to the recipient a "transaction receipt" that contains, in encrypted form, data that the recipient needs in order to take possession of a transaction output. This is burdensome, and implies a high risk of lost funds as a result of lost or uncommunicated receipts.
We propose automated, privacy-preserving methods of scanning for inbound transactions in [BSIP-1203](bsip-1203.md).
#### Backups of Stealth Balances
In [BSIP-1204](bsip-1204.md) we propose standardized derivation of Stealth addresses to enable backup seeds or brainkeys to be used to securely back up a Stealth account prior to first use, enabling recovery in the event of a lost or corrupted hot wallet.
#### Metadata Hiding
Lastly, in [BSIP-1205](bsip-1205.md), we propose methods of hardening wallets against eavesdropping and timing attacks, so that usage patterns and the method used to communicate with the peer-to-peer network do not compromise user privacy. (As an example, a naive wallet might check a users balance by querying the status of a set UTXOs under the user's control, revealing immediately to the network that a given set of UTXOs are "of interest" to a single party.)
## Specifications
## Discussion
## Summary for Shareholders
## Copyright
This document is placed in the public domain.
## See Also
* Phase One of Stealth development: [BSIP-0008](bsip-0008.md)
[1] Confidential Transactions (Greg Maxwell) - https://people.xiph.org/~greg/confidential_values.txt
[2] Confidential Assets (Poelstra, et. al.) - https://blockstream.com/bitcoin17-final41.pdf
[3] Ring Confidential Transactions (Shen Noether) - https://eprint.iacr.org/2015/1098

106
bsip-1201.md Normal file
View file

@ -0,0 +1,106 @@
BSIP: 1201 (unassigned)
Title: New operations for Confidential Asset (CA) transactions
Authors: Christopher J. Sanborn
Status: Draft
Type: Protocol
Created: 2018-01-29
Discussion: <url>
## Abstract
Confidential Assets (CA) [[2]](#see-also) extends Confidential Transactions (CT) [[1]](#see-also) to include asset hiding. The BitShares network already understands and validates CT transactions, but is not yet capable of validating CA transactions. The transaction format will need minor to moderate updating and the validation routines will likewise need updating. We propose to either (a) update op-code 39, 49, and 41 to be CA capable, or (b) define new opcodes for CA stealth operations. The latter option probably affords a cleaner upgrade path. The old opcodes should then be disfavored for user wallet use.
Confidential Assets is a new, but not un-tested, technology. The Elements Project [[3]](#see-also) maintains an experimental implementation [[4]](#see-also) of CA as a Bitcoin side chain. The code for that project is MIT-licensed and can help guide the implementation of CA in the BitShares ecosystem.
_This BSIP is one of several describing_ [Stealth development, Phase II](bsip-1200.md).
## Motivation
A user maintains value-blinded balances on the BitShares blockchain as a collection of Pedersen commitments, which are EC curve points that obscure their committed values by adding a secret blinding factor times a generator point. By keeping the blinding factor secret, the user keeps their balance secret. Meanwhile, balances can be transferred, subdivided, or combined, provided the sum of blinding factors for all inputs to a transaction are equal to the sum of blinding factors of all outputs of a transaction. A user wishing to un-blind and "claim" a balance contained in a Pedersen commitment may do so by revealing the blinding factor for that commitment, which then allows the network to verify the committed amount and credit it to a public balance.
A commitment C is given mathematically by _C = value * H + blinding_factor * G_, where H and G are separate curve point generators with no known divisor between them. Because there is no known multiple _m_ solving _H = m*G_, the _value_ and _blinding_factor_ quantities are effectively independent, which makes _C_ a firm commitment to _value_.
BitShares is a multi-asset chain. The Pedersen commitments implemented in _Stealth Phase I_ commit only to a value amount, and nothing more. For the network to understand *which* asset is represented by a commitment, a plaintext metadata field is associated with the Graphene object for the commitment, containing the asset ID of the blinded asset. This means that the asset type of an individual blinded balance is publicly knowable.
Confidential Assets (CA) introduces a method for using a commitment to a hash of the asset description as a confounding factor similar to the blinding factor, such that, unless one already knows the asset represented by a particular Pedersen commitment, one cannot determine the asset from inspection alone. Furthermore, amounts of differing assets can be combined in a single transaction, so that the asset IDs of the outputs are not individually knowable. Thus, even by tracing the history of a given commitment, one cannot simply divine the asset type by back-tracing to the point where a public asset was blinded, as the history may implicate multiple asset types. When a user wishes to un-blind an asset, he may do so by providing both the value blinding factors and the asset blinding factors for the commitment, so that the network can confirm the contents thereof.
By allowing commitments of differing assets to be mixed together, we achieve two points for privacy: (1) we increase the available mix-in set for diffusion of transaction history, and (2) we make it more difficult for blockchain analysis to determine which assets are being operated on in any given transaction (the more assets involved in the history of a particular commitment, the greater the uncertainty of what the commitment contains).
## Rationale
### _Asset Tags_ and _Asset Commitments_
The existing value-blinded CT transaction capability includes an explicit **asset ID** in the transaction format, and unspent commitments are associated with an explicit clear-text asset ID in the database. For example, querying the blockchain for commitment "024449...8073" returns a structure containing three defining fields:
Field: | Data (Meaning)
:----------:|----------
commitment: | "0244492ceafc9c3d6fab34b4e2912b360a3276560651451580325f754705758073" |
asset_id: | "1.3.0" (Core asset, BTS)
owner: | (Authority struct specifying public key that must sign)
Under CA, the `asset_id` field would be replaced by `asset_commit` which is a commitment to an **asset tag**. The asset tag, denoted *H<sub>A</sub>*, is a curve point produced by a hashing procedure of some defining description of the asset (for example the `asset_id`, "1.3.0", etc.). The asset commitment, denoted *H*, is the sum of *H<sub>A</sub>* and a blind point, e.g., _H = H<sub>A</sub> + r*G_. Under this scheme, a CA commitment in the database would look similar to:
Field: | Data (Meaning)
:------------:|----------
commitment: | "0244492ceafc9c3d6fab34b4e2912b360a3276560651451580325f754705758073"
asset_commit: | "022b607af588386028a97d6bc4be5caddb432340329bc808ba587c0b92ffb1087c"
owner: | (Authority struct specifying public key that must sign)
As can be seen, casual inspection of the blockchain does not reveal the underlying asset, nor even asset tag, since it is commingled with a blinding factor. The only way to know the asset id would be if the commitment were a direct descendent of an asset-issuance transaction (where a public balance was blinded into a value-asset blind CA commitment). However, once a commitment is involved in a transaction involving inputs of multiple asset types, then uncertainty is introduced in the descendent commitments: the asset type will be _one_ of the parent asset types, but which one is unknowable except to parties that know the blinding factors.
_(TODO: QUESTION: How is it ensured that H<sub>A</sub> is a valid curve point? There must be some kind of nonce increment in the hash procedure to reject non-curve points. Find out.)_
### _Range Proofs_ and _Surjection Proofs_
Since the committed values in the Pedersen commitments are unknowable to parties not privy to the blinding factors, there exists the possibility for a transaction resulting in two or more outputs to encode a negative value in one output and an excess positive value in the others, resulting in inflated (i.e., counterfeit) asset supply. To prevent this, transactions with more than a single output are required to provide a **range proof** for each output, which is a zero-knowledge proof that the committed value is in a finite range between zero and an upper bound that won't risk overflow into negative values. (Values are encoded as 256-bit unsigned integers such that very-large integers "wrap around" and behave as negatives. Range proofs typically prove that a committed amount can be represented in 64-bits or less, affording no risk of overflow.) Under CA, the requirement to provide a range proof remains the same as under CT.
A new requirement in CA is the **asset surjection proof**. Similar to range proofs, ASPs prove that a validity contstraint is met on the blinded asset commitments of the transaction outputs. Specifically, it proves that the asset tags of the outputs match the asset tags of the inputs, without revealing what those tags are or which outputs correspond to which inputs. (TODO: preceding is imprecise.)
(TODO: discuss space requirments of ASPs, since they do add to transaction size. Compared to range proofs already included in CT transactions, however, they are comparatively small, except perhaps in the case of a large number of inputs and outputs in a single transaction.)
## Specifications
We propose to add the following three CA operations to the set of valid operations declared in graphene::chain::operation (chain/protocol/operations.hpp). The new CA operations are shown here side by side with their CT equivalents:
Op-Code | Description | Op-Code | Description
:------:|-------------------------------|------------------|----------------------------------
39 | transfer_to_blind_operation | 49 (placeholder) | transfer_to_ca_blind_operation
40 | blind_transfer_operation | 50 (placeholder) | ca_blind_transfer_operation
41 | transfer_from_blind_operation | 51 (placeholder) | transfer_from_ca_blind_operation
| | | 52 (placeholder) | ct_to_ca_blind_transfer_operation
On the left are CT operations, whose outputs are value-blinded commitments. On the right are the corresponding CA operations, whose outputs are value-and-asset-blinded commitments. Of special note is op 52, which takes value-blinded CT inputs and outputs value-and-asset-blinded outputs. (As an alternative, op 50 could be made flexible enough to accept either CT or CA inputs, if this proves feasible.) As CA is seen as an upgrade to CT, no op-code is here proposed for transferring from CA back to CT, however in the event of market demand such an operation could be coded.
#### Proposed operation: transfer_to_ca_blind_operation (Public to Blind)
#### Proposed operation: ca_blind_transfer_operation (Blinded to Blind)
#### Proposed operation: transfer_from_ca_blind_operation (Blind to Public)
## Discussion
### Compatibility with ring-signature scheme
The Op-Code additions and specifications provided in this document do not conflict with or depend on the details of the ring-signature proposals in [BSIP-1202](bsip-1202.md), as they effect different substructures of the Transaction structure, and therefore both proposals can be implemented independently. This document specifies structures within the Operations vector within a Transaction structure, whereas the ring signature scheme would change the Signatures vector.
(TODO: Check whether preceding is true, i.e. that the operation structure is independent of signature method. If it is not true, include here a discussion of what else might need to be included in the structure, so that a decision can be made as to whether the two features would be best developed in parallel, or whether ring-sigs could be implemented subsequently as an "upgrade" to CA.)
#### Asset surjection and compatibility
TODO: Question: Are Asset-Surjection Proofs compatible with a Ring-Sig scheme? I.e., can a prover who is "accusing" unrelated inputs produce the proof even not knowing the blind factors and asset tags of the unrelated inputs?
## Summary for Shareholders
## Copyright
This document is placed in the public domain.
## See Also
[1] Confidential Transactions (Greg Maxwell) - https://people.xiph.org/~greg/confidential_values.txt
[2] Confidential Assets (Poelstra, et. al.) - https://blockstream.com/bitcoin17-final41.pdf
[3] Elements Project - https://elementsproject.org
[4] Elements Project on GitHub - https://github.com/ElementsProject/elements

103
bsip-1202.md Normal file
View file

@ -0,0 +1,103 @@
BSIP: 1202 (unassigned)
Title: Ring signatures for untraceability of Stealth transactions
Authors: Christopher J. Sanborn
Status: Draft
Type: Protocol
Created: 2018-01-29
Discussion: <url>
## Abstract
Confidential Transactions (CT) [[1]](#see-also), (as implemented by [Phase I](bsip-0008.md) of Stealth development), solves the linkability and value-hiding problems, but not the traceability problem. CT transfers are traceable on the blockchain, meaning that for any given transaction, a history of prior transactions can be determined. If the set of antecedents is large, then there is a great degree of plausible-deniability regarding the origins of the hidden assets. However, if the set is small, it is possible to determine with increasing probability where the assets originated from. A solution to this is to “mix” transaction inputs with unrelated users so as to increase the traceability set. Some privacy blockchains rely on a mechanical mixing or “tumbling” process to increase the traceability set, however this approach has drawbacks. Monero has a very clever scheme of using ring signatures to automatically and randomly mix in unrelated inputs on every transaction, guaranteeing that even newly blinded funds are mixed with with inputs having a rich history. It is proposed, as a component of [Stealth development Phase II](bsip-1200.md), to implement a similar mechanism for BitShares.
## Motivation
Stealth can be thought of as a constellation of privacy-preserving features implemented on (or planned for) the BitShares blockchain. "Privacy" here is a set of specific goals:
* Untraceability
* Unlinkability
* Value/Asset hiding
* Anonymity
Although Confidential Transactions (CT) provides good solutions to unlinkability and value hiding, (which together help but do not fully solve anonymity), the transactions currently supported on the network are fully traceable. This means it is possible generate a history all prior transactions leading up to a particular transaction output, including a set of originating transactions wherein public balances were blinded. For outputs which are "close" to their originating transactions, it may be possible possible to identify a small set of non-anonymous originating actors, and to make estimates of the possible maximum value amount of an output (by assuming it can be no larger than the sum of all originating transactions in its history).
What we seek is a method to make it unknowable *which* prior transaction outputs were consumed in the generation of a new transaction output. Although it seems a tall order (how can a node validate that a sum of inputs balances a set of outputs when it is unknown which inputs are involved?), a solution actually comes in the form of a ring signature protocol developed for the Monero project. <!-- TODO: check specific heritage of this protocol -->
The ring signature strategy in Monero has gone through two major developmental stages. In the first stage, transaction amounts were not blinded (although pseudo-blinding was achieved by composing value transfers from an aggregate of round-number individual transactions). In the second stage, the ring signature authorization protocol was combined with Confidential Transactions to form the RingCT protocol [[2]](#see-also), in which transfers are both value-blinded and untraceable. Since BitShares already implements CT, the adoption of RingCT into BitShares Stealth operations can be seen as an improvement upon an existing feature.
## Rationale
Although BitShares is an account-based blockchain, in which value-transfer operations are a simple transfer of balance from one account to another, Stealth operations on the BitShares blockchain instead follow a **UTXO model**. Stealth transactions produce "**transaction outputs**" (TXOs) which represent individual balance amounts under the control of someone possessing the appropriate secret key. These TXOs are "unspent" (UTXOs) until they are involved in a downstream transaction, at which point they are considered destroyed and no longer spendable. (To partially spend a UTXO, a transaction consuming it would need to produce two outputs: one to the intended recipient, and one back to the sender as "change.")
A transaction in a UTXO-based blockchain is simply a list of inputs (UTXOs which will be destroyed) and a list of outputs (newly-generated UTXOs). Validating such a transaction involves confirming that the value sum of inputs equals the value sum of outputs plus fees, and that appropriate authorization is provided for all inputs.
Because the list of inputs is part of the transaction, all UTXOs have a traceable history.
Ring signatures are a signature scheme in which, for a given set of credentials, a signature is provided proving that at least *one* of the credentials authorized the transaction, but it cannot be determined by a third party *which* credential it was that signed it. Thus ring signatures provide **plausible deniability**. All involved credentialed parties can mutually point fingers at each other, saying, "it wasn't me." <!-- CITE -->
Ring signatures can provide untraceability in Stealth transactions in the following way: For a given transaction, a set of inputs is collected which is *larger* than the set needed to cover the the intended transaction outputs. The additional inputs should include inputs for which the spender does not have authorizaton to spend. A signature is provided proving that at minimum *enough* inputs are authorized to cover the outputs, however an external observer cannot determine which inputs are thereby consumed. Double-spending of inputs is prevented by the provision of a "**key image**" for each actually-spent input. A key image is a piece of data that uniquly derives from the consumed input, but which cannot be matched to it. A subsequent spend of the same input would produce the same key image, alerting the network to the attempt at a double spend. Now, the set of inputs to any transaction includes not only the actually-consumed inputs, but also a large set of "red herring" inputs, which achieve two important aims for untraceability:
1. A degree of plausible-deniability for the authorizer of any individual transaction, and
2. An enormously larger set of prior transactions that form the "history" of the transaction, implicating a *much* larger set of originating transactions than is actually involved in the true history of the transaction.
It should be noted that one drowback of this scheme is that it is no longer possible to determine which UTXOs are spent vs. unspent, and this has implications for database pruning. However, the Monero chain has been functioning with this limitation for several years now without hitting a performance bottleneck. Additionally, the Monero team has projected that performance growth will keep pace with database size, even absent pruning of spent TXOs. (CITE). (A review of this projection and discussion of its implication for the BitShares chain is in the Discussion section.)
## Specifications
(Detailed description of RingCT with annotations for how it would be adapted to BitShares Stealth transactions.) [[2]](#see-also)
## Discussion
### Overview of alternative untraceability solutions
(Compare/contrast with other schemes for providing untraceability, including ZeroCoin accumulators, master-node facilitated tumbling, MimbleWimble, etc.)
#### Mimblewimble
* PRO: Supports a sort of automated, non-interactive aggregate signature scheme (end result similar to CoinJoin), facilitating untraceability at the blockchain level (although not necessarily at the network-snooping level).
* CON: Requires communication between sender and recipient.
* [[Jed2016]](#see-also), [[PoelMW]](#see-also)
#### CoinJoin, CoinSwap, etc.
* In [1], Maxwell states "[CT is] compatible with CoinJoin and CoinSwap, allowing for transaction graph privacy as well while simultaneously fixing the most severe limitation of these approaches to privacy (that transaction amounts compromise their privacy)."
* ((This still needs to be researched by this author but I believe these protocols involve mixing with contemporaneous participants, many of whom may be nefarious actors. RingCT allows mixing with historical transactions, and reuse of historical transactions, greatly broadening the set of available mix-in transactions. TODO: confirm this disadvantage.))
* Dash (http://dash.org) uses a system of "master nodes" to coordinate an opt-in mechanism of "pre-washing" coins via several rounds of mixing with other participants where each round of washing is a CoinJoin-like process. (https://dashpay.atlassian.net/wiki/spaces/DOC/pages/1146924/PrivateSend)
#### Accumulator Schemes, e.g. ZeroCoin
* Spending a coin into the accumulator produces receipt that can be used to withdraw a coin from the accumulator later. The withdraw operation cannot be linked to the orignal deposit operation. Untraceability os provided by the fact that the "plausible deniability set" of users who might be responsible for the coin is the set of all users who have deposited coins into the accumulators. This can be a very large set.
* Pros:
* Large deniability set
* Conceptully simple mechanism
* Possible to audit supply
* Cons:
* Depends on a **trusted setup**, which, if compromised, could allow theft or counterfeit of coins
* (NOTE: Announcement by ZCoin team of an upgrade that eliminates need for trusted setup) (CITE)
* [[Yap2017]](#see-also), [[GrothSigma]](#see-also)
* Mechanism to transfer coins between users while the coins are *inside* the accumulator is unclear/unknown (to this author) or impossible. Thus an accumulator may be a good way to wash or hide your own funds, but is not a good solution for creating a balance that one easily use in cash-like user-to-user transactions.
### Scaling challenges in a Ring-Sig scheme
(Discussion of the implications of not pruning spent TXOs.)
## Summary for Shareholders
## Copyright
This document is placed in the public domain.
## See Also
[1] Confidential Transactions (Greg Maxwell) - https://people.xiph.org/~greg/confidential_values.txt
[2] Ring Confidential Transactions (Shen Noether) - https://eprint.iacr.org/2015/1098
[Jed2016] Mimblewimble (Tom Elvis Jedusor) - https://scalingbitcoin.org/papers/mimblewimble.txt
[Poel2016MW] Mimblewimble (Andrew Poelstra) - https://download.wpsoftware.net/bitcoin/wizardry/mimblewimble.pdf
[Yap2017] Zcoin moving beyond trusted setup in Zerocoin (Reuben Yap) - https://zcoin.io/zcoin-moving-beyond-trusted-setup-in-zerocoin/
[GrothSigma] - One-out-of-Many Proofs: Or How to Leak a Secret and Spend a Coin (Jens Groth and Markulf Kohlweiss) - https://eprint.iacr.org/2014/764.pdf

34
bsip-1204.md Normal file
View file

@ -0,0 +1,34 @@
BSIP: 1204 (unassigned)
Title: Deterministic addresses for Stealth wallets
Authors: Christopher J. Sanborn
Status: Draft
Type: Informational
Created: 2018-01-29
Discussion: <url>
## Abstract
To simplify a wallet owner's backup burden by documenting and standardizing key derivation for Stealth balances from the same backup seeds used to generate the user's regular account keys.
## Motivation
Current wallet implementations (e.g. the CLI wallet and Agorise's extensions to the UI wallet) generate a new Brain Key for each Stealth "account" (defined as a confidential balance under the control of a single private key). Since creating a confidential account is a purely client-side activity, (in contrast with a regular account which is registered on the blockchain), there is no automatic association between a confidential balance and a regular account that ostensibly "owns" it, and a backup burden is created for each new confidential balance.
It would be desireable to give the user the ability to maintain all of her accounts and balances under the control of a single backup key seed or brain key, so that the backup burden can be satisfied just once, at the creation of the user's first regular account. The derivation schemes defined under Bitcoin's BIP-44 provide a natural mechanism for this, and Satoshi Lab's SLIP-48 already define derivation paths for owner, active, and memo keys on BitShares and similar networks.
We propose here:
(1) To define additional derivation paths for Stealth accounts, and,
(2) For backwards compatibility with existing accounts secured by Brain Key, to standardise and document a distinct procedure for deriving Stealth keys from Brain Keys so that the same Brain Key that secures a user's regular account can also be used to secure their confidential balances, if the user desires.
## Rationale
## Specifications
## Discussion
## Summary for Shareholders
## Copyright
This document is placed in the public domain.
## See Also

30
bsip-1205.md Normal file
View file

@ -0,0 +1,30 @@
BSIP: 1205 (unassigned)
Title: Metadata hiding via Garlic Routing and other means
Authors: Christopher J. Sanborn
Status: Draft
Type: Informational
Created: 2018-01-29
Discussion: <url>
## Abstract
To provide an overview of strategies that can be used by wallets to prevent leaking of sensitive metadata, e.g. your interest in particular balances on the blockchain, to third parties that may be monitoring network traffic, or to potentially compromised nodes on the BitShares p2p network.
## Motivation
Querying a p2p node to check your confidential balances reveals your interest in particular commitments and threatens anonymity by establishing a link between an IP address and a commitment set. New anonymity technologies such as Garlic routing and i2p can be used to ensure that neither network monitoring nor a compromised p2p node can determine the origin of a request regarding a particular set of commitments, thus protecting anonymity.
Additionally, querying a discrete set of commitments undermines confidential unlinkability. Unlinkability is the inability to determine that multiple independent commitments are controlled by the same party. Although not perfect, a partial solution to this is to use Bloom filters to query a superset of commitments, so that the p2p node will return a mix of linked commitments as well as random commitments, making it difficult for an external observer to establish which commitments are actually of interest to the querying party and which are included by the filter serendipitously.
There may also exist other strategies of merit to protect unlinkability and privacy generally.
## Rationale
## Specifications
## Discussion
## Summary for Shareholders
## Copyright
This document is placed in the public domain.
## See Also