zcash-hackworks / zbxcat

A work-in-progress for Zcash Bitcoin Cross-Chain Atomic Transactions
Other
60 stars 20 forks source link

Calculate locktime confidence across chains #35

Open prestwich opened 7 years ago

prestwich commented 7 years ago

Eventually we need reliable estimates of how often X Bitcoin blocks will occur before Y Zcash blocks, so that we can set safe locktimes on each chain. With the help of a statistician friend, I wrote a script to calculate that.

import operator as op
import math

# StackExchange ncr magic
def ncr(n, r):
    r = min(r, n - r)
    if r == 0:
        return 1
    numer = reduce(op.mul, xrange(n, n - r, -1))
    denom = reduce(op.mul, xrange(1, r + 1))
    return numer // denom

# Number of Bitcoin blocks for estimation
c1b = 100.0
# Bitcoin's rate (1 block per 600 seconds)
c1r = 1/600.0

# Number of Zcash blocks for estimation
c2b = 300.0
# Zcash's rate (1 block per 150 seconds)
c2r = 1/150.0

sum = 0.0

for k in range(int(c1b), int(c1b + c2b)):
    term_one = ncr(int(c1b + c2b - 1), int(k))
    term_two = math.pow(c1r / (c1r + c2r), k)
    term_three = math.pow(c2r / (c1r + c2r), c1b + c2b - 1 - k)

    sum += term_one * term_two * term_three

print sum
leto commented 7 years ago

I am seeing 0.00799453086688 as a result of this script on Python 2.7.13 .

To clarify, what are the units of the result?

prestwich commented 7 years ago

The result is the probability that 100 bitcoin blocks elapse before 300 zcash blocks. In this case, 7.99%.

You can swap out c1b and c2b to calculate probability for different numbers of blocks on each chain.

For real-life applications, we should probably target something like 0.0000001 (99.99999% confidence that the locktimes will expire in the expected order).

leto commented 7 years ago

@frdwrd thanks, I appreciate the answer. This code will be useful for various coins doing XCAT, thanks.

prestwich commented 7 years ago

Worth noting that this is less reliable if the coins have strongly correlated hashrates (like bitcoin cash and bitcoin).

leto commented 7 years ago

@frdwrd thanks for pointing that out. For myself, I would be interested in KMD<->HUSH and ZEC<->HUSH because we are performing XCATs between those coins with barterDEX. Perhaps a brave soul will improve this into a script that prints out all the useful data for lots of coins 😺