Giter VIP home page Giter VIP logo

btcrelay's Introduction

Join the chat at https://gitter.im/ethereum/btcrelay

BTC Relay is an Ethereum contract for Bitcoin SPV. The main functionality it provides are:

  1. verification of a Bitcoin transaction
  2. optionally relay the Bitcoin transaction to any Ethereum contract
  3. storage of Bitcoin block headers
  4. inspection of the latest Bitcoin block header stored in the contract

BTC Relay contract address and ABI:

The address and ABI is all that's needed to use BTC Relay, in addition to the API documentation below.

API

verifyTx(rawTransaction, transactionIndex, merkleSibling, blockHash)

Verifies the presence of a transaction on the Bitcoin blockchain, primarily that the transaction is on Bitcoin's main chain and has at least 6 confirmations.

  • rawTransaction - raw bytes of the transaction
  • transactionIndex - transaction's index within the block, as int256
  • merkleSibling - array of the sibling hashes comprising the Merkle proof, as int256[]
  • blockHash - hash of the block that contains the transaction, as int256

Returns uint256

  • hash of the verified Bitcoin transaction
  • 0 if rawTransaction is exactly 64 bytes in length or fails verification

Note: See examples/sampleCall.html including use of bitcoin-proof for constructing merkleSibling.


relayTx(rawTransaction, transactionIndex, merkleSibling, blockHash, contractAddress)

Verifies a Bitcoin transaction per verifyTx() and relays the verified transaction to the specified Ethereum contract.

  • rawTransaction - raw bytes of the transaction
  • transactionIndex - transaction's index within the block, as int256
  • merkleSibling - array of the sibling hashes comprising the Merkle proof, as int256[]
  • blockHash - hash of the block that contains the transaction, as int256
  • contractAddress - address of the processor contract that will receive the verified Bitcoin transaction, as int256

The processor contract at contractAddress should have a function of signature processTransaction(bytes rawTransaction, uint256 transactionHash) returns (int256) and is what will be invoked by relayTx if the transaction passes verification. For examples, see BitcoinProcessor.sol and testnetSampleRelayTx.html.

Returns int256

  • value returned by the processor contract's processTransaction function
  • or ERR_RELAY_VERIFY, see constants.se

Note: Callers cannot be 100% certain when an ERR_RELAY_VERIFY occurs because it may also have been returned by processTransaction(). Callers should be aware of the contract that they are relaying transactions to, and understand what the processor contract's processTransaction method returns.


storeBlockHeader(blockHeader)

Store a single block header if it is valid, such as a valid Proof-of-Work and the previous block it reference exists.

  • blockHeader - raw bytes of the block header (not the hex string, but the actual bytes).

Returns int256

  • block height of the header if it was successfully stored
  • 0 otherwise

bulkStoreHeader(bytesOfHeaders, numberOfHeaders)

Store multiple block headers if they are valid.

  • bytesOfHeaders - raw bytes of the block headers (not the hex string, but the actual bytes), with one following immediately the other.
  • numberOfHeaders - int256 count of the number of headers being stored.

Returns int256

  • block height of the last header if all block headers were successfully stored
  • 0 if any of the block headers were not successfully stored

Note: See deploy/relayTest/testBulkDeploy.yaml for an example of the data for storing multiple headers. Also, to avoid exceeding Ethereum's block gas limit, a guideline is to store only 5 headers at time.


getBlockHeader(blockHash)

Get the 80 byte block header for a given blockHash. A payment value of getFeeAmount(blockHash) must be provided in the transaction.

  • blockHash - hash of the block as int256

Returns bytes

  • block header, always as 80 bytes (all zeros if header does not exist)
  • or 0 (as a single byte) if insufficient payment is provided

getBlockHash(blockHeight)

Get the block hash for a given blockHeight.

  • blockHeight - height of the block as int256. Minimum value is 1.

Returns int256

  • block hash
  • 0 if not found

getAverageChainWork()

Returns the difference between the chainWork of the latest block and the 10th block prior.

This is provided in case an Ethereum contract wants to use the chainWork or Bitcoin network difficulty (which can be derived) as a data feed.


getBlockchainHead(), getLastBlockHeight(), others

getBlockchainHead - returns the hash of the latest block, asint256

getLastBlockHeight - returns the block height of the latest block, as int256

See BitcoinRelayAbi.js for other APIs and testnetContractStatus.html for an example of calling some of them.


Incentives

The following APIs are described in Incentives for Relayers below.

storeBlockWithFee(), changeFeeRecipient(), getFeeRecipient(), getFeeAmount(), getChangeRecipientFee()


Examples

Examples for how to use BTC Relay include:


How to use BTC Relay

The easiest way to use BTC Relay is via relayTx because the ABI can remain on the frontend.

testnetSampleRelayTx.html shows how a Bitcoin transaction from the frontend can be passed (relayed) to an Ethereum contract.

See other examples for other ways to use BTC Relay and the docs for FAQ.

Libs/utils

Thanks to those who wrote these:


Incentives for Relayers

Relayers are those who submit block headers to BTC Relay. To incentivize the community to be relayers, and thus allow BTC Relay to be autonomous and up-to-date with the Bitcoin blockchain, Relayers can call storeBlockWithFee. The Relayer will be the getFeeRecipient() for the block they submit, and when any transactions are verified in the block, or the header is retrieved via getBlockHeader, the Relayer will be rewarded with getFeeAmount().

To avoid a relayer R1 from setting excessive fees, it is possible for a relayer R2 to changeFeeRecipient(). R2 must specify a fee lower than what R1 specified, and pay getChangeRecipientFee() to R1, but now R2 will be the getFeeRecipient() for the block and will earn all future getFeeAmount().

With this background, here are API details for incentives.

storeBlockWithFee(blockHeader, fee)

Store a single block header (like storeBlockHeader) and set a fee that will be charged for verifications that use blockHeader.

  • blockHeader - raw bytes of the block header (not the hex string, but the actual bytes).
  • fee - int256 amount in wei.

Returns int256

  • block height of the header if it was successfully stored
  • 0 otherwise

changeFeeRecipient(blockHash, fee, recipient)

Set the fee and recipient for a given blockHash. The call must have msg.value of at least getChangeRecipientFee(), and must also specify a fee lower than the current getFeeAmount(blockHash).

  • blockHash - hash of the block as int256.
  • fee - int256 amount in wei.
  • recipient - int256 address of the recipient of fees.

Returns int256

  • 1 if the fee and recipient were successfully set
  • 0 otherwise

getFeeRecipient(blockHash)

Get the address that receives the fees for a given blockHash.

  • blockHash - hash of the block as int256.

Returns int256

  • address of the recipient

getFeeAmount(blockHash)

Get the fee amount in wei for verifications using a given blockHash.

  • blockHash - hash of the block as int256.

Returns int256

  • amount of the fee in wei.

getChangeRecipientFee()

Get the amount of wei required that must be sent to BTC Relay when calling changeFeeRecipient.

Returns int256

  • amount of wei

Development

Requirements

Running tests

Exclude slow tests:

py.test test/ -s -m "not slow"

Run slow tests without veryslow tests

py.test test/ -s -m "slow and not veryslow"

All tests:

py.test test/ -s

License

See full MIT License including:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

btcrelay's People

Contributors

achempion avatar caktux avatar ethers avatar gitter-badger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

btcrelay's Issues

Provide binary release.

It appears (based on the Readme) that this tool is only available as a Python script. It would be nice if it was released as a binary so I could run it without having to install Python.

The binaries should be available on all major OSs.

receipt verification function

I think what we need is a receipt verification function.
input: the target BTC address, amount of BTC received at the target BTC address, number of confirmations
output: true if the amount of BTC has been received at the target BTC address with the specified number of confirmations; false otherwise.

a subroutine is also needed:
input: BTC tx hash
output: how deep is the tx embedded in the main branch? of course, the returned value reflects the "current" status. for a current ETH block height, there is a corresponding BTC block height.

any comment? can we have such a function?

and there is an ultimate question: why do we trust the function? is it trustworthy?

Clamping of gas price

https://github.com/ethereum/btcrelay/blob/develop/incentive.se#L32-L35

        if tx.gasprice < (1023*gLastGasPrice/1024) || tx.gasprice > (1025*gLastGasPrice/1024):
            currGP = gLastGasPrice
        else:
            currGP = tx.gasprice

The else clause should be either 1023*gLastGasPrice/1024 or 1025*gLastGasPrice/1024 (So that honest gas prices can affect the trend of the gas price, instead of just using the last gas price which may have been "set" by an "attacker")

m_saveAncestors and hashprevblockarg

BtcChain.se, line 23, m_saveAncestors

Takes hashprevblockarg as argument, but two lines later uses blockHashArg as hashPrevBlock, ignoring the parameter completely (line 25).

Use of BTCRelay without paying fees

With Metropolis, there will be a new opcode, REVERT (ethereum/EIPs#206) and RETURNDATA (ethereum/EIPs#211).

The REVERT opcode will function as a throw, reverting state-changes, but will not burn the remaining gas. Additionally, it can return some data, in order to provide the callee with information about the error.

Unfortunately, this EVM-change undermines the model for synchronous oracles which accept payment; it's possible to

  1. Make a call to BTCFreelay
  2. Make a call to InternalCall
    3. Perform call to BTCRelay for verification, along with payment
    4. Perform revert along with the response from BTCRelay

This would revert the payment(s), but still grant access to the return value.

Note: Even without RETURNDATA , it would still be possible to perform this attack, albeit with less data being extracted. Example gist showing how to 'freeload' on btcrelay using revert without returndata: https://gist.github.com/holiman/51f9b02b64f864b896129d329757460c .

Note 2, this can also be performed already today, using a regular throw, but the attack is quite 'messy' since it needs to handle several intricate cases of OOG due to remaining gas being discarded at every throw.

I'm filing this as an issue, even if it's not yet implemented, so there can be a discussion about possible future modifications that can be made. Also, posting it as a 'known issue' here makes in not eligible for a reward in the bug bounty.

Inaccuracy in initialization of highScore

self.highScore = 1 should more accurately be self.highScore = chainWork
https://github.com/ethereum/btcrelay/blob/develop/btcrelay.se#L67

But it doesn't affect things because scorePrevBlock (not highScore) is used to compute the next scoreBlock:

scoreBlock = scorePrevBlock + difficulty

and scorePrevBlock
scorePrevBlock = m_getScore(hashPrevBlock)

Note: there are also tests that verified that scores are expected. (Though there must be a missing/wront test that highScore is correct value after setInitialParent)

Contract doesn't have source in Etherscan

Whoever deployed the "live" contract mentioned in README.md, please also do the Etherscan verification: https://etherscan.io/verifyContract?a=0x41f274c0023f83391de4e0733c609df5a124c3d4

It's slightly misleading to call the contract live though when the last storeBlockHeader was 94 days ago... hope it gets better; after all, a lot of projects are out there to solve inter-blockchain communication. This solution is already running, but no one seems to be using it.

Solidity library that parses a Bitcoin transaction

For those that are interested, a Solidity library that parses a Bitcoin transaction would be a great compliment to BTC Relay. The first version could parse a "standard" Bitcoin transaction that just has 1 input and 1 output, like the following in Serpent:
https://github.com/ethereum/btcrelay/blob/master/example-btc-eth/btcSpecialTx.se

A more general, but outdated (since it accepts input as hex string instead of bytes) example is:
https://github.com/ethereum/btcrelay/blob/master/example-btc-eth/btcTx.se

Head prioritization

when there are 2 blocks that can be at the Head of btcrelay's internal "blockchain", should btcrelay always prioritize the head hash that is smallest in value...

Etherscan.io

name: Bug Report
description: File a bug report
title: "[Bug]: "
labels: ["bug", "triage"]
assignees:

  • octocat
    body:
  • type: markdown
    attributes:
    value: |
    Thanks for taking the time to fill out this bug report!
  • type: input
    id: contact
    attributes:
    label: Contact Details
    description: How can we get in touch with you if we need more info?
    placeholder: [email protected]
    validations:
    required: false
  • type: textarea
    id: what-happened
    attributes:
    label: What happened?
    description: Also tell us, what did you expect to happen?
    placeholder: Tell us what you see!
    value: "A bug happened!"
    validations:
    required: true
  • type: dropdown
    id: version
    attributes:
    label: Version
    description: What version of our software are you running?
    options:
    - 1.0.2 (Default)
    - 1.0.3 (Edge)
    validations:
    required: true
  • type: dropdown
    id: browsers
    attributes:
    label: What browsers are you seeing the problem on?
    multiple: true
    options:
    - Firefox
    - Chrome
    - Safari
    - Microsoft Edge
  • type: textarea
    id: logs
    attributes:
    label: Relevant log output
    description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
    render: shell
  • type: checkboxes
    id: terms
    attributes:
    label: Code of Conduct
    description: By submitting this issue, you agree to follow our Code of Conduct
    options:
    - label: I agree to follow this project's Code of Conduct
    required: true

Relayer_0

BITCOIN_MAINNET = 'btc'
BITCOIN_TESTNET = 'testnet'
SLEEP_TIME = 5 * 60 # 5 mins. If changing, check retry logic
GAS_FOR_STORE_HEADERS = 1200000 # it should take less than 1M gas, but buffer to avoid running out
CHUNK_SIZE = 5 # number of headers to fetch at a time
CHUNK_RANGE = range(CHUNK_SIZE)

using the return code from the contract that the tx is relayed to

def relayTx(txBytes:str, txIndex, sibling:arr, txBlockHash, contract):
    txHash = self.verifyTx(txBytes, txIndex, sibling, txBlockHash,
value=msg.value)
    if txHash != 0:
        returnCode = contract.processTransaction(txBytes, txHash)
        log(type=RelayTransaction, txHash, returnCode)
        return(returnCode)

    log(type=RelayTransaction, 0, ERR_RELAY_VERIFY)
    return(ERR_RELAY_VERIFY)

The 'contract' in this case, if he returns ERR_RELAY_VERIFY, won't that
look very much like the bitcoin Tx was not verified, even though it was
successfully verified... Have to consider fixing this

High gas costs

It costs about 0.04$ to add a new header in gas costs. This makes it expensive to get it current (about 10k blocks behind)- any ideas to optimize to make it easier to keep up to date?

Thanks

consider reserving some gas for relayTx

A) relayTx passes all gas to callee contract <- current behavior.
There's 2 cases:
A1) gas is enough for relayTx and callee so the log is done.
A2) gas is all consumed by callee contract, so tx is OOG and no log generated.

B) Suggested behavior is for relayTx to reserve some gas for itself and provide/limit a specific amount to callee contract.
2 cases:
B1) gas is enough for relayTx and gas amount to callee is enough so the log is done.
B2) gas is enough for relayTx but provided gas to callee contract is insufficient, so OOG should be handled by relayTx and a log still generated.

So consider updating the relayTx interface to take an additional uint param, which is how much gas to provide to processTransaction

Website is not open-source (and has a bad link)

Hey there,

I noticed that btcrelay.org has a link that says "For further details, view this DEVCON1 presentation". But the link has no href value. I believe it should point here.

I went to look for the site so I could send a PR, but I couldn't find it! So the real issue is, the site isn't open-source :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.