The Stacks 2.0 blockchain implementation

Overview

Stacks 2.0

Reference implementation of the Stacks blockchain in Rust.

Stacks 2.0 is a layer-1 blockchain that connects to Bitcoin for security and enables decentralized apps and predictable smart contracts. Stacks 2.0 implements Proof of Transfer (PoX) mining that anchors to Bitcoin security. Leader election happens at the Bitcoin blockchain and Stacks (STX) miners write new blocks on the separate Stacks blockchain. With PoX there is no need to modify Bitcoin to enable smart contracts and apps around it. See this page for more details and resources.

CircleCI

Repository

Blockstack Topic/Tech Where to learn more more
Stacks 2.0 master branch
Stacks 1.0 legacy branch
Use the package our core docs
Develop a Blockstack App our developer docs
Use a Blockstack App our browser docs
Blockstack PBC the company our website

Release Schedule and Hotfixes

Normal releases in this repository that add features such as improved RPC endpoints, improved boot-up time, new event observer fields or event types, etc., are released on a monthly schedule. The currently staged changes for such releases are in the develop branch. It is generally safe to run a stacks-node from that branch, though it has received less rigorous testing than release tags. If bugs are found in the develop branch, please do report them as issues on this repository.

For fixes that impact the correct functioning or liveness of the network, hotfixes may be issued. These are patches to the main branch which are backported to the develop branch after merging. These hotfixes are categorized by priority according to the following rubric:

  • High Priority. Any fix for an issue that could deny service to the network as a whole, e.g., an issue where a particular kind of invalid transaction would cause nodes to stop processing requests or shut down unintentionally. Any fix for an issue that could cause honest miners to produce invalid blocks.
  • Medium Priority. Any fix for an issue that could cause miners to waste funds.
  • Low Priority. Any fix for an issue that could deny service to individual nodes.

Versioning

This repository uses a 5 part version number.

X.Y.Z.A.n

X = 2 and does not change in practice unless there’s another Stacks 2.0 type event
Y increments on consensus-breaking changes
Z increments on non-consensus-breaking changes that require a fresh chainstate (akin to semantic MAJOR)
A increments on non-consensus-breaking changes that do not require a fresh chainstate, but introduce new features (akin to semantic MINOR)
n increments on patches and hot-fixes (akin to semantic PATCH)

For example, a node operator running version 2.0.10.0.0 would not need to wipe and refresh their chainstate to upgrade to 2.0.10.1.0 or 2.0.10.0.1. However, upgrading to 2.0.11.0.0 would require a new chainstate.

Roadmap

Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions.

See SIP 000 for more details.

The SIPs are now located in the stacksgov/sips repository as part of the Stacks Community Governance organization.

Testnet versions

  • Krypton is a Stacks 2 testnet with a fixed, two-minute block time, called regtest. Regtest is generally unstable for regular use, and is reset often. See the regtest documentation for more information on using regtest.

  • Xenon is the Stacks 2 public testnet, which runs PoX against the Bitcoin testnet. It is the full implementation of the Stacks 2 blockchain, and should be considered a stable testnet for developing Clarity smart contracts. See the testnet documentation for more information on the public testnet.

  • Mainnet is the fully functional Stacks 2 blockchain, see the Stacks overview for information on running a Stacks node, mining, stacking, and writing Clarity smart contracts.

Getting started

Download and build stacks-blockchain

The first step is to ensure that you have Rust and the support software installed.

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

For building on Windows, follow the rustup installer instructions at https://rustup.rs/

From there, you can clone this repository:

git clone --depth=1 https://github.com/blockstack/stacks-blockchain.git

cd stacks-blockchain

Then build the project:

cargo build

Run the tests:

cargo test testnet  -- --test-threads=1

Encode and sign transactions

Here, we have generated a keypair that will be used for signing the upcoming transactions:

cargo run --bin blockstack-cli generate-sk --testnet

# Output
# {
#  secretKey: "b8d99fd45da58038d630d9855d3ca2466e8e0f89d3894c4724f0efc9ff4b51f001",
#  publicKey: "02781d2d3a545afdb7f6013a8241b9e400475397516a0d0f76863c6742210539b5",
#  stacksAddress: "ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH"
# }

This keypair is already registered in the testnet-follower-conf.toml file, so it can be used as presented here.

We will interact with the following simple contract kv-store. In our examples, we will assume this contract is saved to ./kv-store.clar:

(define-map store { key: (string-ascii 32) } { value: (string-ascii 32) })

(define-public (get-value (key (string-ascii 32)))
    (match (map-get? store { key: key })
        entry (ok (get value entry))
        (err 0)))

(define-public (set-value (key (string-ascii 32)) (value (string-ascii 32)))
    (begin
        (map-set store { key: key } { value: value })
        (ok true)))

We want to publish this contract on chain, then issue some transactions that interact with it by setting some keys and getting some values, so we can observe read and writes.

Our first step is to generate and sign, using your private key, the transaction that will publish the contract kv-store. To do that, we will use the subcommand:

cargo run --bin blockstack-cli publish --help

With the following arguments:

cargo run --bin blockstack-cli publish b8d99fd45da58038d630d9855d3ca2466e8e0f89d3894c4724f0efc9ff4b51f001 515 0 kv-store ./kv-store.clar --testnet

The 515 is the transaction fee, denominated in microSTX. Right now, the testnet requires one microSTX per byte minimum, and this transaction should be less than 515 bytes. The third argument 0 is a nonce, that must be increased monotonically with each new transaction.

This command will output the binary format of the transaction. In our case, we want to pipe this output and dump it to a file that will be used later in this tutorial.

cargo run --bin blockstack-cli publish b8d99fd45da58038d630d9855d3ca2466e8e0f89d3894c4724f0efc9ff4b51f001 515 0 kv-store ./kv-store.clar --testnet | xxd -r -p > tx1.bin

Run the testnet

You can observe the state machine in action locally by running:

cargo stacks-node start --config=./testnet/stacks-node/conf/testnet-follower-conf.toml

testnet-follower-conf.toml is a configuration file that you can use for setting genesis balances or configuring Event observers. You can grant an address an initial account balance by adding the following entries:

[[ustx_balance]]
address = "ST2VHM28V9E5QCRD6C73215KAPSBKQGPWTEE5CMQT"
amount = 100000000

The address field is the Stacks testnet address, and the amount field is the number of microSTX to grant to it in the genesis block. The addresses of the private keys used in the tutorial below are already added.

Publish your contract

Assuming that the testnet is running, we can publish our kv-store contract.

In another terminal (or file explorer), you can move the tx1.bin generated earlier, to the mempool:

curl -X POST -H "Content-Type: application/octet-stream" --data-binary @./tx1.bin http://localhost:20443/v2/transactions

In the terminal window running the testnet, you can observe the state machine's reactions.

Reading from / Writing to the contract

Now that our contract has been published on chain, let's try to submit some read / write transactions. We will start by trying to read the value associated with the key foo.

To do that, we will use the subcommand:

cargo run --bin blockstack-cli contract-call --help

With the following arguments:

cargo run --bin blockstack-cli contract-call b8d99fd45da58038d630d9855d3ca2466e8e0f89d3894c4724f0efc9ff4b51f001 500 1 ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH kv-store get-value -e \"foo\" --testnet | xxd -r -p > tx2.bin

contract-call generates and signs a contract-call transaction.

We can submit the transaction by moving it to the mempool path:

curl -X POST -H "Content-Type: application/octet-stream" --data-binary @./tx2.bin http://localhost:20443/v2/transactions

Similarly, we can generate a transaction that would be setting the key foo to the value bar:

cargo run --bin blockstack-cli contract-call b8d99fd45da58038d630d9855d3ca2466e8e0f89d3894c4724f0efc9ff4b51f001 500 2 ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH kv-store set-value -e \"foo\" -e \"bar\" --testnet | xxd -r -p > tx3.bin

And submit it by moving it to the mempool path:

curl -X POST -H "Content-Type: application/octet-stream" --data-binary @./tx3.bin http://localhost:20443/v2/transactions

Finally, we can issue a third transaction, reading the key foo again, for ensuring that the previous transaction has successfully updated the state machine:

cargo run --bin blockstack-cli contract-call b8d99fd45da58038d630d9855d3ca2466e8e0f89d3894c4724f0efc9ff4b51f001 500 3 ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH kv-store get-value -e \"foo\" --testnet | xxd -r -p > tx4.bin

And submit this last transaction by moving it to the mempool path:

curl -X POST -H "Content-Type: application/octet-stream" --data-binary @./tx4.bin http://localhost:20443/v2/transactions

Congratulations, you can now write your own smart contracts with Clarity.

Platform support

Officially supported platforms: Linux 64-bit, MacOS 64-bit, Windows 64-bit.

Platforms with second-tier status (builds are provided but not tested): MacOS Apple Silicon (ARM64), Linux ARMv7, Linux ARM64.

For help cross-compiling on memory-constrained devices, please see the community supported documentation here: Cross Compiling.

Community

Beyond this Github project, Blockstack maintains a public forum and an opened Discord channel. In addition, the project maintains a mailing list which sends out community announcements.

The greater Blockstack community regularly hosts in-person meetups. The project's YouTube channel includes videos from some of these meetups, as well as video tutorials to help new users get started and help developers wrap their heads around the system's design.

Further Reading

You can learn more by visiting the Blockstack Website and checking out the documentation:

You can also read the technical papers:

If you have high-level questions about Blockstack, try searching our forum and start a new question if your question is not answered there.

Contributing

Tests and Coverage

PRs must include test coverage. However, if your PR includes large tests or tests which cannot run in parallel (which is the default operation of the cargo test command), these tests should be decorated with #[ignore]. If you add #[ignore] tests, you should add your branch to the filters for the all_tests job in our circle.yml (or if you are working on net code or marf code, your branch should be named such that it matches the existing filters there).

A test should be marked #[ignore] if:

  1. It does not always pass cargo test in a vanilla environment (i.e., it does not need to run with --test-threads 1).
  2. Or, it runs for over a minute via a normal cargo test execution (the cargo test command will warn if this is not the case).

Formatting

This repository uses the default rustfmt formatting style. PRs will be checked against rustfmt and will fail if not properly formatted.

You can check the formatting locally via:

cargo fmt --all -- --check

You can automatically reformat your commit via:

cargo fmt --all

Mining

Stacks tokens (STX) are mined by transferring BTC via PoX. To run as a miner, you should make sure to add the following config fields to your config file:

[node]
# Run as a miner
miner = True
# Bitcoin private key to spend
seed = "YOUR PRIVATE KEY"
# How long to wait for microblocks to arrive before mining a block to confirm them (in milliseconds)
wait_time_for_microblocks = 10000
# Run as a mock-miner, to test mining without spending BTC.
# Mutually exclusive with `miner`.
#mock_miner = True

[miner]
# Smallest allowed tx fee, in microSTX
min_tx_fee = 100
# Time to spend on the first attempt to make a block.
# This can be small, so your node gets a block-commit into the Bitcoin mempool early.
first_attempt_time_ms: 1000
# Time to spend on subsequent attempts to make a block.
# This can be bigger -- new block-commits will be RBF'ed.
subsequent_attempt_time_ms: 60000

You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs:

$ head -n 100 /path/to/your/node/logs | grep -i utxo
INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: <redacted>
INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node

Configuring Cost and Fee Estimation

Fee and cost estimators can be configure via the config section [fee_estimation]:

[fee_estimation]
cost_estimator = naive_pessimistic
fee_estimator = scalar_fee_rate
cost_metric = proportion_dot_product
log_error = true
enabled = true

Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. log_error controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting enabled = false turns off the cost estimators. Cost estimators are not consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them.

Non-Consensus Breaking Release Process

For non-consensus breaking releases, this project uses the following release process:

  1. The release must be timed so that it does not interfere with a prepare phase. The timing of the next Stacking cycle can be found here. A release to mainnet should happen at least 24 hours before the start of a new cycle, to avoid interfering with the prepare phase. So, start by being aware of when the release can happen.

  2. Before creating the release, the release manager must determine the version number for this release. The factors that determine the version number are discussed in Versioning. We assume, in this section, that the change is not consensus-breaking. So, the release manager must first determine whether there are any "non-consensus-breaking changes that require a fresh chainstate". This means, in other words, that the database schema has changed. Then, the release manager should determine whether this is a feature release, as opposed to a hot fix or a patch. Given the answers to these questions, the version number can be computed.

  3. The release manager enumerates the PRs or issues that would block the release. A label should be applied to each such issue/PR as 2.0.x.y.z-blocker. The release manager should ping these issue/PR owners for updates on whether or not those issues/PRs have any blockers or are waiting on feedback.

  4. The release manager should open a develop -> master PR. This can be done before all the blocker PRs have merged, as it is helpful for the manager and others to see the staged changes.

  5. The release manager must update the CHANGELOG.md file with summaries what was Added, Changed, and Fixed. The pull requests merged into develop can be found here. Note, however, that GitHub apparently does not allow sorting by merge time, so, when sorting by some proxy criterion, some care should be used to understand which PR's were merged after the last develop -> master release PR. This CHANGELOG.md should also be used as the description of the develop -> master so that it acts as release notes when the branch is tagged.

  6. Once the blocker PRs have merged, the release manager will create a new tag by manually triggering the stacks-blockchain Github Actions workflow against the develop branch, inputting the release candidate tag, 2.0.x.y.z-rc0, in the Action's input textbox.

  7. Once the release candidate has been built, and docker images, etc. are available, the release manager will notify various ecosystem participants to test the release candidate on various staging infrastructure:

    1. Stacks Foundation staging environments.
    2. Hiro PBC regtest network.
    3. Hiro PBC testnet network.
    4. Hiro PBC mainnet mock miner.

    The release candidate should be announced in the #stacks-core-devs channel in the Stacks Discord. For coordinating rollouts on specific infrastructure, the release manager should contact the above participants directly either through e-mail or Discord DM. The release manager should also confirm that the built release on the Github releases page is marked as Pre-Release.

  8. The release manager will test that the release candidate successfully syncs with the current chain from genesis both in testnet and mainnet. This requires starting the release candidate with an empty chainstate and confirming that it synchronizes with the current chain tip.

  9. If bugs or issues emerge from the rollout on staging infrastructure, the release will be delayed until those regressions are resolved. As regressions are resolved, additional release candidates should be tagged. The release manager is responsible for updating the develop -> master PR with information about the discovered issues, even if other community members and developers may be addressing the discovered issues.

  10. Once the final release candidate has rolled out successfully without issue on the above staging infrastructure, the release manager tags 2 additional stacks-blockchain team members to review the develop -> master PR.

  11. Once reviewed and approved, the release manager merges the PR, and tags the release via the stacks-blockchain Github action by clicking "Run workflow" and providing the release version as the tag (e.g., 2.0.11.1.0) This creates a release and release images. Once the release has been created, the release manager should update the Github release text with the CHANGELOG.md "top-matter" for the release.

Copyright and License

The code and documentation copyright are attributed to blockstack.org for the year of 2020.

This code is released under the GPL v3 license, and the docs are released under the Creative Commons license.

Comments
  • 'Uninstalling a distutils installed project' error when installing blockstack

    'Uninstalling a distutils installed project' error when installing blockstack

    I am on macOS Sierra: 10.12.5, running Python 2.7. Had some issues installing in OSX, and ended up finding this was the issue (when running sudo pip install blockstack --upgrade):

        DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
        Uninstalling six-1.4.1:
    Exception:
    Traceback (most recent call last):
      File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
        status = self.run(options, args)
      File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 342, in run
        prefix=options.prefix_path,
      File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 778, in install
        requirement.uninstall(auto_confirm=True)
      File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 754, in uninstall
        paths_to_remove.remove(auto_confirm)
      File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
        renames(path, new_path)
      File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
        shutil.move(old, new)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
        copy2(src, real_dst)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
        copystat(src, dst)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
        os.chflags(dst, st.st_flags)
    OSError: [Errno 1] Operation not permitted: '/tmp/pip-W_MEda-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'
    

    After attempting to narrow the cause and doing a bit of searching, I was able to get blockstack working in the CLI.

    I used pip install --ignore-installed six or more generally pip install --ignore-installed ${PACKAGE_NAME}

    source

    Even though this is not directly related to blockstack (it's a common error when uninstalling packages on newer versions of OSX), I am making this issue so it's easier for others in the community to find. Closing now. Thanks!

    opened by sdtsui 77
  • Supported TLDs?

    Supported TLDs?

    For DNSChain to resolve domains in blockstore, we need to know the TLDs that are supported.

    You can't say "any domains" because you cannot use existing ones (you will break the internet if you try that).

    So what TLDs should DNSChain query blockstore for?

    opened by taoeffect 48
  • Mempool improvements

    Mempool improvements

    This is the cleaned up version of simple-iterator discussed in #3326 and #3313.

    To-do before checking in:

    • verify that a snapshot chainstate creates a DB with the right query plan
      • can do as part of bringing up mock miner from snapshot.. then can check the query plan
    L1 Working Group 2.05.0.5.0 
    opened by obycode 43
  • Discussion: name expiration periods

    Discussion: name expiration periods

    We've noticed one topic that keeps coming up - the name expiration period for the .id namespace.

    The name expiration period for the .id namespace (which is meant to be used for personal usernames) was initially set for 1 year, which means that names would expire after a year if they weren't renewed.

    While this period seems to work very well for domain names, some have argued that it is an undue burden for users to have to renew their usernames after a year. Based on this, we'd like to ask the community whether the expiration period for .id or some other namespace for usernames should be 1 year, 2 years, or more.

    Keep in mind that this parameter is a tradeoff between (1) the convenience of users to not to have to renew their names very often and (2) the ability for the system to turnover unused usernames. With this in mind, please answer the poll question below.

    What should the name expiration period be for a namespace for people and their usernames?

    • 1 year
    • 1.5 years
    • 2 years
    • 5 years
    • Infinity years (names never expire)
    • Other
    opened by shea256 41
  • Events/pox 2

    Events/pox 2

    Description

    This PR does the following:

    • adds a synthetic transaction type such that the auto unlock events are captured within a transaction receipt
    • adds print events to the pox-2 contract for operations that affect a user's locked token state:
      • handle-unlock (this is the auto-unlock function called by the node)
      • stack-stx
      • stack-extend
      • stack-increase
      • delegate-stack-stx
      • delegate-stack-extend
      • delegate-stack-increase

    I also cleaned up the clarity docs file a little bit.

    I tested that the functions emit the expected print event in pox_2_tests.rs.

    Applicable issues

    • fixes #3289
    stacks-2.1 event-stream 
    opened by pavitthrap 34
  • min_confs: 0 doesn't work

    min_confs: 0 doesn't work

    I tried to do a registration where balance hasn't yet confirmed and it failed because of inadequate balance.

    post body to /v1/names:

    {"name":"devname5.id","owner_address":"14zF6PTKgd2DCaNvap345udaNp6p4U2E3M","zonefile":"$ORIGIN devname5.id\n$TTL 3600\n_http._tcp\tIN\tURI\t10\t1\t\"https://www.dropbox.com/s/1lpz8509ggilaav/profile.json?dl=1\"\n\n","min_confs":0}
    

    Response (500):

    {"error": "Failed to register name: Address 37tbGfinfPk6h4NCpXRQHAQT9cEWWWGW89 does not have enough balance (need 495479, have 450000)."}
    

    State of address 37tbGfinfPk6h4NCpXRQHAQT9cEWWWGW89 @ block height 452703 when registration transaction was attempted:

    {"addrStr":"37tbGfinfPk6h4NCpXRQHAQT9cEWWWGW89","balance":0.0045,"balanceSat":450000,"totalReceived":0.0045,"totalReceivedSat":450000,"totalSent":0,"totalSentSat":0,"unconfirmedBalance":0.0015,"unconfirmedBalanceSat":150000,"unconfirmedTxApperances":1,"txApperances":1,"transactions":["5eac394e958feacf464c4a5abddf2b981583bd632fbf0a389b4d371f93b65173","f7b18eba18fc0648cc069d13f86d3e278b8637b5804403681cf46a0d8e2e40b6"]}
    
    screen shot 2017-02-12 at 4 52 59 pm
    opened by larrysalibra 34
  • [bns] Function to get all names associated with a principal

    [bns] Function to get all names associated with a principal

    I was playing around with how to possibly integrate read-only calls into the explorer related to BNS, and it seems that it's not currently possible to call a function to return any names associated with a given principal. I think this would be very useful for clients such as the explorer and the wallet(s). I spoke with Ludo this morning and he said that while we don't currently have a function for that, it is technically possible.

    If there was a read only call that provided this functionality, it might provide a good interim state of useful functionality while we wait for the stacks-blockchain-api to surface similar features.

    BNS 
    opened by aulneau 33
  • Unique Stacks address format

    Unique Stacks address format

    Moved from: https://github.com/blockstack/blockstack-core/issues/822#issuecomment-391680586

    I think from a product and user experience perspective it makes more sense to use different address formats for the different token types.

    There are a number of reasons for this. One reason is that without its "own" format like ethereum has it's own 0x format, it doesn't seem like a full blown separate coin.

    Another reason is to avoid user confusion. A bitcoin address is a bitcoin address. If i want to ask someone for the account to which they'd like to send me Stacks, do I ask them for a bitcoin address? How can someone looking at the string determine if the wallet software that generated supports stacks or only bitcoin?

    opened by larrysalibra 28
  • Decide APIv1 endpoints

    Decide APIv1 endpoints

    My understanding is that APIv1 endpoints are pretty much decided (in offline discussions). I'm documenting the current state here.

    @jcnelson said on Slack

    endpoints are:
    * registering a name: `POST /api/v1/names` with JSON payload `{'name': '...'}`
    * transferring a name to an address:  `PUT /api/v1/names/:name/owner` with JSON payload `{'owner': '...'}`
    * getting the state of all pending transactions:  `GET /api/v1/blockchain/bitcoin/pending`
    * getting all names owned by an address: `GET /api/v1//addresses/:address/names`
    * getting the address of a name, as well as its zonefile: `GET /api/v1/names/:name`
    * getting the address of the owner and wallet of the blockstack node: `GET /api/v1/node/wallet/public
    

    I'd also like to identify the must-haves from nice-to-have, so we can focus on the import endpoints first.

    opened by muneeb-ali 28
  • Trait handling for Clarity 2

    Trait handling for Clarity 2

    Description

    Improvements to traits for Clarity 2

    Applicable issues

    • fixes #3251

    Additional info (benefits, drawbacks, caveats)

    In progress

    • [x] Clean up implementation
    • [x] Make these changes only affect Clarity2
    • [ ] Check coverage

    Checklist

    • [x] Test coverage for new or modified code paths
    • [x] Changelog is updated
    • [x] Required documentation changes (e.g., docs/rpc/openapi.yaml and rpc-endpoints.md for v2 endpoints, event-dispatcher.md for new events)
    • [x] New clarity functions have corresponding PR in clarity-benchmarking repo
    • [ ] New integration test(s) added to bitcoin-tests.yml
    stacks-2.1 
    opened by obycode 27
  • [Proposal] JSON-RPC API

    [Proposal] JSON-RPC API

    Note: descriptions, names, types, formatting -- all WIP

    Methods (prod)

    • call_func(contract identifier, function name, function args) -> ok(function return data), err(function_not_found, parser, type checker, or runtime error)
    • deploy_contract(contract identifier, contract source code) -> ok(contract address), err(parser, type checker, or runtime error)
    • get_deployment_cost(contract source code) -> ok(stacks tokens int), err(parser, or type checker error)
    • send_transaction(contract identifier, function name, function args) -> ok(tx_receipt ?), err(type checker or runtime error)
    • get_map_entry(contact identifier, map name, map key value) -> ok(value data), err()
    • get_contract_source(contract identifier) -> ok(source string), err(contract_not_found)

    Methods (dev mode only)

    • dev_mine_block(optional unix timestamp) -> ok(block number)

    Object Types

    Responses

    • Errors
      • parse_error(msg)
      • type_error(msg)
      • runtime_error(msg)
      • map_not_found
      • map_entry_not_found
      • contract_not_found
      • function_not_found
    • tx_receipt(cost, tx_hash)
    documentation 
    opened by zone117x 27
  • Miner doesn't commit due to Bad nonce

    Miner doesn't commit due to Bad nonce

    Describe the bug Miner doesn't commit due to error: Bad nonce: origin account [miner_stx_address] nonce of tx [txid] is [N] (expected [N+1])

    Steps To Reproduce Problem occurs when there was a transaction associated with the miner STX wallet included in a latest block which increased wallet nonce.

    Expected behavior Miner increments nonce correctly

    opened by MaksimalistT 0
  • Make `BurnchainParameters` TOML-configurable.. possibly even `PoxConstants`

    Make `BurnchainParameters` TOML-configurable.. possibly even `PoxConstants`

    Is your feature request related to a problem? Please describe. Right now, BurnchainParameters is not TOML configurable. https://github.com/stacks-network/stacks-blockchain/blob/a0393e47452ae45eea645d792717d41035320961/src/burnchains/mod.rs#L98

    This can be difficult for running a custom testnet (like for Stacks 2.1), because you might want to change first_block_height on the fly when trying out new test nets.

    The same could arguably be said for PoxConstants, for which we recently wanted to set v1_unlock_height.

    The call stacks for BurnchainParameters::from_params and PoxConstants::new are documented in https://github.com/stacks-network/stacks-blockchain/discussions/3411

    Describe the solution you'd like Make BurnchainParameters configurable in the TOML file, and maybe even PoxConstants.

    Describe alternatives you've considered The current way to configure BurnchainParameters is to change the Rust code.

    Additional context https://github.com/stacks-network/stacks-blockchain/discussions/3411

    opened by gregorycoppola 1
  • Feat/check pox 2 params

    Feat/check pox 2 params

    This PR adds a config method that will validate the PoX 2 and epoch parameters. Specifically:

    • v1_unlock_height must be strictly after the epoch 2.1 start height, and cannot fall on a reward cycle start boundary if it's in the subsequent reward cycle from the epoch 2.1 start.
    • If v1_unlock_height falls in the same reward cycle as the epoch 2.1 start height, then the epoch 2.1 start height must be in the reward phase -- ideally, the very first block.

    The reasons for this are that the v1_unlock_height value is used to determine which PoX contract to query to determine a reward cycle's reward set. So, pox-2 must be instantiated before the PoX anchor block for its first reward cycle is mined. This also means that v1_unlock_height must not be at the very beginning of a reward cycle -- reward cycles start at the first block, not the zeroth block, of the reward cycle, so the reward cycle of a v1_unlock_height that fell on a sortition height such that sortition_height % reward_cycle_len == 0 would be in the preceding reward cycle.

    This PR makes the both the mocknet and Neon nodes panic early if these conditions are not met.

    I'm going to see if all integration tests continue to pass with the settings we've given them. But in the mean time, feel free to try this out. This is meant to address #3407.

    stacks-2.1 
    opened by jcnelson 3
  • [Stacks 2.1] Miner error for epoch `start_height` and `pox_2_activation` config values

    [Stacks 2.1] Miner error for epoch `start_height` and `pox_2_activation` config values

    Initial context for this issue in the comments from another issue: https://github.com/stacks-network/stacks-blockchain/issues/3261#issuecomment-1310606024

    A regtest+krypton miner will error and fail to mine with certain epoch start_height and pox_2_activation (i.e. v1_unlock_height) config.toml values.

    Once the pox_2_activation height is reached, the error Failure fetching recipient set: ChainstateError(ClarityError(Interpreter(Unchecked(NoSuchContract("ST000000000000000000002AMW42H.pox-2"))))) is logged in an indefinite loop.

    Some config values do work, but approximately 3/4ths of different combinations of these config values will trigger this error.

    See the full debug log output here from when this error happens.

    Go to the end of the log to see where the miner loops with the error:

    ERRO [1668778959.365802] [testnet/stacks-node/src/neon_node.rs:1674] [miner-block-http://0.0.0.0:20443] Relayer: Failure fetching recipient set: ChainstateError(ClarityError(Interpreter(Unchecked(NoSuchContract("ST000000000000000000002AMW42H.pox-2")))))
    

    See here for the config.toml file used, and here for the btc-mining-script.sh script used.

    I've also added pushed a docker setup so anyone can easily reproduce this locally, see https://github.com/zone117x/stacks-regtest-env/pull/16

    opened by zone117x 2
  • [Stacks 2.1] Regtest+Krypton miner does not produce blocks with empty mempool

    [Stacks 2.1] Regtest+Krypton miner does not produce blocks with empty mempool

    @lgalabru and I both ran into what appears to be a regression with regtest+krypton mining.

    When the mempool is empty, the miner stalls rather than mining empty blocks. This behavior seems to have been introduced from the last merge from master into next a couple weeks ago.

    A workaround for this is to add the following to config.toml:

    [node]
    wait_time_for_blocks = 0 # fixes stalled miner
    

    Unclear to me if this is intended new behavior or a bug.

    opened by zone117x 2
Releases(2.05.0.5.1)
Owner
Stacks
Smart contracts for Bitcoin
Stacks
Futures implementation for JSON-RPC

futures-jsonrpc Futures + JSON-RPC A lightweight remote procedure call protocol. It is designed to be simple! And, with futures, even more flexible! T

Victor Lopes 12 May 19, 2022
🥧 Savoury implementation of the QUIC transport protocol and HTTP/3

quiche is an implementation of the QUIC transport protocol and HTTP/3 as specified by the IETF. It provides a low level API for processing QUIC packet

Cloudflare 6.9k Nov 27, 2022
Futures-based QUIC implementation in Rust

Pure-rust QUIC protocol implementation Quinn is a pure-rust, future-based implementation of the QUIC transport protocol undergoing standardization by

null 2.4k Nov 27, 2022
neqo — an Implementation of QUIC written in Rust

Neqo, an Implementation of QUIC written in Rust To run test HTTP/3 programs (neqo-client and neqo-server): cargo build ./target/debug/neqo-server [::]

Mozilla 1.5k Nov 21, 2022
The Rust Implementation of libp2p networking stack.

Central repository for work on libp2p This repository is the central place for Rust development of the libp2p spec. Warning: While we are trying our b

libp2p 2.9k Dec 3, 2022
A pure Rust implementation of WebRTC API

A pure Rust implementation of WebRTC API

WebRTC.rs 2.4k Nov 26, 2022
Backroll is a pure Rust implementation of GGPO rollback networking library.

backroll-rs Backroll is a pure Rust implementation of GGPO rollback networking library. Development Status This is still in an untested alpha stage. A

Hourai Teahouse 268 Nov 19, 2022
A working demo of RustDesk server implementation

A working demo of RustDesk server implementation This is a super simple working demo implementation with only one relay connection allowed, without NA

RustDesk 454 Nov 22, 2022
axum-server is a hyper server implementation designed to be used with axum framework.

axum-server axum-server is a hyper server implementation designed to be used with axum framework. Features Conveniently bind to any number of addresse

null 75 Nov 28, 2022
Official Implementation of Findora Network.

Findora Platform Wiki Contribution Guide Licensing The primary license for Platform is the Business Source License 1.1 (BUSL-1.1), see LICENSE. Except

Findora Foundation 60 Nov 4, 2022
A small holepunching implementation written in Rust (UDP)

rust-udp-holepunch A small holepunching implementation written in Rust (UDP) Prerequisites Your rendezvous server must lay in a network which doesn't

Amit Katz 5 Aug 16, 2022
An implementation of the CESS network supported by CESS LAB.

--------- ?? ---------An infrastructure of decentralized cloud data network built with Substrate-------- ?? -------- ---------------- ?? -------------

Cess Project 244 Nov 19, 2022
Rust implementation of PRECIS Framework: Preparation, Enforcement, and Comparison of Internationalized Strings in Application Protocols

Rust PRECIS Framework libray PRECIS Framework: Preparation, Enforcement, and Comparison of Internationalized Strings in Application Protocols as descr

Santiago Carot-Nemesio 1 Oct 20, 2022
Implementation of algorithms for Domain Name System (DNS) Cookies construction

DNS Cookie RFC7873 left the construction of Server Cookies to the discretion of the DNS Server (implementer) which has resulted in a gallimaufry of di

Rushmore Mushambi 2 Feb 4, 2022
A high performence Socks5 proxy server with bind/reverse support implementation by Rust.

rsocx A high performence Socks5 proxy server with bind/reverse support implementation by Rust Features Async-std No unsafe code Single executable Linu

b23r0 248 Nov 11, 2022
Interactive bind/reverse PTY shell with Windows&Linux support implementation by Rust.

Cliws Lightweight interactive bind/reverse PTY shell with Windows&Linux support implementation by Rust. Features WebSocket Full pty support: VIM, SSH,

b23r0 215 Dec 3, 2021
Rustus - TUS protocol implementation in Rust.

Rustus Tus protocol implementation written in Rust. Features This implementation has several features to make usage as simple as possible. Rustus is r

Pavel Kirilin 68 Nov 21, 2022
A super naive, (possibly unreliable), VPN implementation.

Poor Man's VPN A super naive, (possibly unreliable), VPN implementation. Try on Docker Containers You can test the VPN on docker containers. up.sh scr

algon 2 Sep 7, 2022
An implementation of the ZITADEL gRPC API in Rust.

An implementation of the ZITADEL gRPC API in Rust. Complemented with other useful elements such as ServiceAccount auth.

Christoph Bühler 10 Nov 11, 2022