Browse Source

First Crowdin updates (#1308)

* New translations proof-of-transfer.md (Hindi)

* New translations running-mainnet-node.md (French)

* New translations running-mainnet-node.md (Spanish)

* New translations running-mainnet-node.md (German)

* New translations running-mainnet-node.md (Japanese)

* New translations running-mainnet-node.md (Korean)

* New translations running-mainnet-node.md (Russian)

* New translations running-mainnet-node.md (Turkish)

* New translations overview.md (Chinese Simplified)

* New translations overview.md (Russian)

* New translations mining.md (Japanese)

* New translations network.md (Japanese)

* New translations mining.md (Korean)

* New translations mining.md (Russian)

* New translations mining.md (Turkish)

* New translations mining.md (Chinese Simplified)

* New translations mining.md (Portuguese, Brazilian)

* New translations mining.md (Indonesian)

* New translations mining.md (Hindi)

* New translations network.md (French)

* New translations network.md (Spanish)

* New translations network.md (German)

* New translations network.md (Korean)

* New translations overview.md (Korean)

* New translations network.md (Russian)

* New translations network.md (Turkish)

* New translations network.md (Chinese Simplified)

* New translations network.md (Portuguese, Brazilian)

* New translations network.md (Indonesian)

* New translations network.md (Hindi)

* New translations overview.md (French)

* New translations overview.md (Spanish)

* New translations overview.md (German)

* New translations overview.md (Japanese)

* New translations running-mainnet-node.md (Chinese Simplified)

* New translations running-mainnet-node.md (Portuguese, Brazilian)

* New translations technical-specs.md (Spanish)

* New translations stacks-blockchain-api.md (Japanese)

* New translations stacks-blockchain-api.md (Korean)

* New translations stacks-blockchain-api.md (Russian)

* New translations stacks-blockchain-api.md (Turkish)

* New translations stacks-blockchain-api.md (Chinese Simplified)

* New translations stacks-blockchain-api.md (Portuguese, Brazilian)

* New translations stacks-blockchain-api.md (Indonesian)

* New translations stacks-blockchain-api.md (Hindi)

* New translations technical-specs.md (French)

* New translations technical-specs.md (German)

* New translations stacks-blockchain-api.md (Spanish)

* New translations technical-specs.md (Japanese)

* New translations technical-specs.md (Korean)

* New translations technical-specs.md (Russian)

* New translations technical-specs.md (Turkish)

* New translations technical-specs.md (Chinese Simplified)

* New translations technical-specs.md (Portuguese, Brazilian)

* New translations technical-specs.md (Indonesian)

* New translations technical-specs.md (Hindi)

* New translations testnet.md (French)

* New translations testnet.md (Spanish)

* New translations stacks-blockchain-api.md (German)

* New translations stacks-blockchain-api.md (French)

* New translations running-mainnet-node.md (Indonesian)

* New translations running-testnet-node.md (Indonesian)

* New translations running-mainnet-node.md (Hindi)

* New translations running-testnet-node.md (French)

* New translations running-testnet-node.md (Spanish)

* New translations running-testnet-node.md (German)

* New translations running-testnet-node.md (Japanese)

* New translations running-testnet-node.md (Korean)

* New translations running-testnet-node.md (Russian)

* New translations running-testnet-node.md (Turkish)

* New translations running-testnet-node.md (Chinese Simplified)

* New translations running-testnet-node.md (Portuguese, Brazilian)

* New translations running-testnet-node.md (Hindi)

* New translations stacking.md (Hindi)

* New translations stacking.md (French)

* New translations stacking.md (Spanish)

* New translations stacking.md (German)

* New translations stacking.md (Japanese)

* New translations stacking.md (Korean)

* New translations stacking.md (Russian)

* New translations stacking.md (Turkish)

* New translations stacking.md (Chinese Simplified)

* New translations stacking.md (Portuguese, Brazilian)

* New translations stacking.md (Indonesian)

* New translations testnet.md (German)

* New translations testnet.md (Japanese)

* New translations principals.md (Chinese Simplified)

* New translations overview.md (Indonesian)

* New translations overview.md (Hindi)

* New translations principals.md (French)

* New translations principals.md (Spanish)

* New translations principals.md (German)

* New translations principals.md (Japanese)

* New translations principals.md (Korean)

* New translations principals.md (Russian)

* New translations principals.md (Turkish)

* New translations principals.md (Portuguese, Brazilian)

* New translations overview.md (Chinese Simplified)

* New translations principals.md (Indonesian)

* New translations principals.md (Hindi)

* New translations tokens.md (French)

* New translations tokens.md (Spanish)

* New translations tokens.md (German)

* New translations tokens.md (Japanese)

* New translations tokens.md (Korean)

* New translations tokens.md (Russian)

* New translations tokens.md (Turkish)

* New translations tokens.md (Chinese Simplified)

* New translations overview.md (Portuguese, Brazilian)

* New translations overview.md (Turkish)

* New translations testnet.md (Korean)

* New translations transactions.md (Korean)

* New translations testnet.md (Russian)

* New translations testnet.md (Turkish)

* New translations testnet.md (Chinese Simplified)

* New translations testnet.md (Portuguese, Brazilian)

* New translations testnet.md (Indonesian)

* New translations testnet.md (Hindi)

* New translations transactions.md (French)

* New translations transactions.md (Spanish)

* New translations transactions.md (German)

* New translations transactions.md (Japanese)

* New translations transactions.md (Russian)

* New translations overview.md (Russian)

* New translations transactions.md (Turkish)

* New translations transactions.md (Chinese Simplified)

* New translations transactions.md (Portuguese, Brazilian)

* New translations transactions.md (Indonesian)

* New translations transactions.md (Hindi)

* New translations overview.md (French)

* New translations overview.md (Spanish)

* New translations overview.md (German)

* New translations overview.md (Japanese)

* New translations overview.md (Korean)

* New translations tokens.md (Portuguese, Brazilian)

* New translations tokens.md (Indonesian)

* New translations values.md (Turkish)

* New translations tokens.md (Hindi)

* New translations 404.md (French)

* New translations values.md (Hindi)

* New translations values.md (Indonesian)

* New translations values.md (Chinese Simplified)

* New translations values.md (Portuguese, Brazilian)

* New translations values.md (Russian)

* New translations values.md (Korean)

* New translations values.md (Japanese)

* New translations values.md (German)

* New translations values.md (Spanish)

* New translations values.md (French)

* New translations index.md (German)

* New translations contributing.md (Portuguese, Brazilian)

* New translations contributing.md (Indonesian)

* New translations contributing.md (Hindi)

* New translations index.md (French)

* New translations index.md (Spanish)

* New translations index.md (Indonesian)

* New translations index.md (Japanese)

* New translations index.md (Korean)

* New translations index.md (Russian)

* New translations index.md (Turkish)

* New translations index.md (Chinese Simplified)

* New translations index.md (Portuguese, Brazilian)

* New translations contributing.md (Turkish)

* New translations contributing.md (Chinese Simplified)

* New translations 404.md (Hindi)

* New translations contributing.md (Russian)

* New translations contributing.md (Korean)

* New translations contributing.md (Japanese)

* New translations contributing.md (German)

* New translations contributing.md (Spanish)

* New translations contributing.md (French)

* New translations 404.md (Indonesian)

* New translations 404.md (Portuguese, Brazilian)

* New translations 404.md (Chinese Simplified)

* New translations 404.md (Turkish)

* New translations 404.md (Russian)

* New translations 404.md (Korean)

* New translations 404.md (Japanese)

* New translations 404.md (German)

* New translations 404.md (Spanish)

* New translations index.md (Hindi)

* updated lint and lint fix

* update node version test

* New translations bns-contract.md (French)

* New translations bns-contract.md (Spanish)

* New translations bns-contract.md (German)

* New translations bns-contract.md (Japanese)

* New translations bns-contract.md (Korean)

* New translations bns-contract.md (Russian)

* New translations bns-contract.md (Turkish)

* New translations glossary.md (Japanese)

* New translations bns-contract.md (Chinese Simplified)

* New translations glossary.md (French)

* New translations glossary.md (Spanish)

* New translations glossary.md (German)

* New translations glossary.md (Korean)

* New translations glossary.md (Russian)

* New translations glossary.md (Turkish)

* New translations glossary.md (Chinese Simplified)

* New translations glossary.md (Portuguese, Brazilian)

* New translations glossary.md (Indonesian)

* New translations glossary.md (Hindi)

* New translations language-functions.md (French)

* New translations language-functions.md (Spanish)

* New translations bns-contract.md (Portuguese, Brazilian)

* New translations bns-contract.md (Indonesian)

* New translations bns-contract.md (Hindi)

* New translations language-functions.md (Chinese Simplified)

* New translations language-functions.md (Hindi)

* New translations language-functions.md (Indonesian)

* New translations language-functions.md (Portuguese, Brazilian)

* New translations language-functions.md (German)

* New translations language-functions.md (Turkish)

* New translations language-functions.md (Russian)

* New translations language-functions.md (Korean)

* New translations language-functions.md (Japanese)

* New translations language-keywords.md (French)

* New translations language-keywords.md (Spanish)

* New translations stacking-contract.md (Russian)

* New translations stacking-contract.md (French)

* New translations stacking-contract.md (Spanish)

* New translations stacking-contract.md (German)

* New translations stacking-contract.md (Japanese)

* New translations stacking-contract.md (Korean)

* New translations stacking-contract.md (Turkish)

* New translations stacking-contract.md (Chinese Simplified)

* New translations stacking-contract.md (Portuguese, Brazilian)

* New translations stacking-contract.md (Indonesian)

* New translations stacking-contract.md (Hindi)

* New translations language-keywords.md (German)

* New translations language-overview.md (German)

* New translations language-keywords.md (Japanese)

* New translations language-keywords.md (Korean)

* New translations language-keywords.md (Russian)

* New translations language-keywords.md (Turkish)

* New translations language-keywords.md (Chinese Simplified)

* New translations language-keywords.md (Portuguese, Brazilian)

* New translations language-keywords.md (Indonesian)

* New translations language-keywords.md (Hindi)

* New translations language-overview.md (French)

* New translations language-overview.md (Spanish)

* New translations language-overview.md (Japanese)

* New translations language-overview.md (Korean)

* New translations language-overview.md (Russian)

* New translations language-overview.md (Turkish)

* New translations language-overview.md (Chinese Simplified)

* New translations language-overview.md (Portuguese, Brazilian)

* New translations language-overview.md (Indonesian)

* New translations language-overview.md (Hindi)
patch-criadoperez4
Jonathon Hammond 3 years ago
committed by GitHub
parent
commit
f017d6b867
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      package.json
  2. 24
      src/pages/de/404.md
  3. 27
      src/pages/de/build-apps/overview.md
  4. 65
      src/pages/de/build-apps/references/authentication.md
  5. 244
      src/pages/de/build-apps/references/bns.md
  6. 92
      src/pages/de/build-apps/references/gaia.md
  7. 268
      src/pages/de/contributing.md
  8. 18
      src/pages/de/index.md
  9. 24
      src/pages/de/references/bns-contract.md
  10. 51
      src/pages/de/references/deploy-tips.md
  11. 24
      src/pages/de/references/faqs.md
  12. 8
      src/pages/de/references/glossary.md
  13. 10
      src/pages/de/references/language-functions.md
  14. 10
      src/pages/de/references/language-keywords.md
  15. 84
      src/pages/de/references/language-overview.md
  16. 23
      src/pages/de/references/language-types.md
  17. 24
      src/pages/de/references/stacking-contract.md
  18. 513
      src/pages/de/references/stacks-node-configuration.md
  19. 352
      src/pages/de/start-mining/mainnet.md
  20. 343
      src/pages/de/start-mining/testnet.md
  21. 211
      src/pages/de/understand-stacks/accounts.md
  22. 110
      src/pages/de/understand-stacks/microblocks.md
  23. 74
      src/pages/de/understand-stacks/mining.md
  24. 147
      src/pages/de/understand-stacks/network.md
  25. 70
      src/pages/de/understand-stacks/overview.md
  26. 57
      src/pages/de/understand-stacks/proof-of-transfer.md
  27. 188
      src/pages/de/understand-stacks/running-mainnet-node.md
  28. 141
      src/pages/de/understand-stacks/running-testnet-node.md
  29. 131
      src/pages/de/understand-stacks/stacking.md
  30. 46
      src/pages/de/understand-stacks/stacks-blockchain-api.md
  31. 72
      src/pages/de/understand-stacks/technical-specs.md
  32. 27
      src/pages/de/understand-stacks/testnet.md
  33. 43
      src/pages/de/understand-stacks/transactions.md
  34. 58
      src/pages/de/write-smart-contracts/overview.md
  35. 238
      src/pages/de/write-smart-contracts/principals.md
  36. 72
      src/pages/de/write-smart-contracts/tokens.md
  37. 305
      src/pages/de/write-smart-contracts/values.md
  38. 24
      src/pages/es/404.md
  39. 27
      src/pages/es/build-apps/overview.md
  40. 65
      src/pages/es/build-apps/references/authentication.md
  41. 244
      src/pages/es/build-apps/references/bns.md
  42. 92
      src/pages/es/build-apps/references/gaia.md
  43. 268
      src/pages/es/contributing.md
  44. 18
      src/pages/es/index.md
  45. 24
      src/pages/es/references/bns-contract.md
  46. 51
      src/pages/es/references/deploy-tips.md
  47. 24
      src/pages/es/references/faqs.md
  48. 8
      src/pages/es/references/glossary.md
  49. 10
      src/pages/es/references/language-functions.md
  50. 10
      src/pages/es/references/language-keywords.md
  51. 84
      src/pages/es/references/language-overview.md
  52. 23
      src/pages/es/references/language-types.md
  53. 24
      src/pages/es/references/stacking-contract.md
  54. 513
      src/pages/es/references/stacks-node-configuration.md
  55. 352
      src/pages/es/start-mining/mainnet.md
  56. 343
      src/pages/es/start-mining/testnet.md
  57. 211
      src/pages/es/understand-stacks/accounts.md
  58. 110
      src/pages/es/understand-stacks/microblocks.md
  59. 74
      src/pages/es/understand-stacks/mining.md
  60. 147
      src/pages/es/understand-stacks/network.md
  61. 70
      src/pages/es/understand-stacks/overview.md
  62. 57
      src/pages/es/understand-stacks/proof-of-transfer.md
  63. 188
      src/pages/es/understand-stacks/running-mainnet-node.md
  64. 141
      src/pages/es/understand-stacks/running-testnet-node.md
  65. 131
      src/pages/es/understand-stacks/stacking.md
  66. 46
      src/pages/es/understand-stacks/stacks-blockchain-api.md
  67. 72
      src/pages/es/understand-stacks/technical-specs.md
  68. 27
      src/pages/es/understand-stacks/testnet.md
  69. 43
      src/pages/es/understand-stacks/transactions.md
  70. 58
      src/pages/es/write-smart-contracts/overview.md
  71. 238
      src/pages/es/write-smart-contracts/principals.md
  72. 72
      src/pages/es/write-smart-contracts/tokens.md
  73. 305
      src/pages/es/write-smart-contracts/values.md
  74. 24
      src/pages/fr/404.md
  75. 27
      src/pages/fr/build-apps/overview.md
  76. 65
      src/pages/fr/build-apps/references/authentication.md
  77. 244
      src/pages/fr/build-apps/references/bns.md
  78. 92
      src/pages/fr/build-apps/references/gaia.md
  79. 268
      src/pages/fr/contributing.md
  80. 18
      src/pages/fr/index.md
  81. 24
      src/pages/fr/references/bns-contract.md
  82. 51
      src/pages/fr/references/deploy-tips.md
  83. 24
      src/pages/fr/references/faqs.md
  84. 8
      src/pages/fr/references/glossary.md
  85. 10
      src/pages/fr/references/language-functions.md
  86. 10
      src/pages/fr/references/language-keywords.md
  87. 84
      src/pages/fr/references/language-overview.md
  88. 23
      src/pages/fr/references/language-types.md
  89. 24
      src/pages/fr/references/stacking-contract.md
  90. 513
      src/pages/fr/references/stacks-node-configuration.md
  91. 352
      src/pages/fr/start-mining/mainnet.md
  92. 343
      src/pages/fr/start-mining/testnet.md
  93. 211
      src/pages/fr/understand-stacks/accounts.md
  94. 110
      src/pages/fr/understand-stacks/microblocks.md
  95. 74
      src/pages/fr/understand-stacks/mining.md
  96. 147
      src/pages/fr/understand-stacks/network.md
  97. 70
      src/pages/fr/understand-stacks/overview.md
  98. 57
      src/pages/fr/understand-stacks/proof-of-transfer.md
  99. 188
      src/pages/fr/understand-stacks/running-mainnet-node.md
  100. 141
      src/pages/fr/understand-stacks/running-testnet-node.md

6
package.json

@ -2,7 +2,7 @@
"name": "@blockstack/docs",
"version": "1.0.0",
"engines": {
"node": ">=12.0.0"
"node": ">=14.0.0"
},
"dependencies": {
"@docsearch/css": "^1.0.0-alpha.27",
@ -124,8 +124,8 @@
"lint": "yarn lint:eslint && yarn lint:prettier",
"lint:eslint": "eslint \"src/**/*.{ts,tsx}\" -f unix",
"lint:fix": "eslint \"src/**/*.{ts,tsx}\" -f unix --fix",
"lint:prettier": "prettier --check \"src/**/*.{ts,tsx,md,mdx}\" *.js",
"lint:prettier:fix": "prettier --write \"src/**/*.{ts,tsx,md,mdx}\" *.js",
"lint:prettier": "prettier --check \"src/**/*.{ts,tsx,mdx}\" \"src/pages/en/**/*.md\" *.js",
"lint:prettier:fix": "prettier --write \"src/**/*.{ts,tsx,mdx}\" \"src/pages/en/**/*.md\" *.js",
"typecheck": "tsc --noEmit",
"typecheck:watch": "npm run typecheck -- --watch",
"check:urls": "find . -type f -name '*.md' ! -path './node_modules/*' ! -path './_site/*' | xargs -L1 npx markdown-link-check -q -c mlc_config.json",

24
src/pages/de/404.md

@ -0,0 +1,24 @@
---
title: Page not found
description: The page you're looking for isn't here.
---
## Whoops
Looks like the page you are looking for isn't here.
-> Developer content has recently moved to [docs.hiro.so](https://docs.hiro.so/). For more information on the content move, see [this post](https://forum.stacks.org/t/the-evolution-of-the-stacks-documentation-and-a-new-hiro-docs-site/12343) on the Stacks forum. Check for your content at [docs.hiro.so](https://docs.hiro.so/) or ask in Discord if you believe you have reached this page in error.
Try out some of these popular pages:
## Understand Stacks
[@page-reference | grid] | /understand-stacks/overview, /understand-stacks/proof-of-transfer, /understand-stacks/testnet
## Write smart contracts
[@page-reference | grid] | /write-smart-contracts/overview
## Start mining
[@page-reference | grid] | /start-mining/mainnet, /start-mining/testnet

27
src/pages/de/build-apps/overview.md

@ -0,0 +1,27 @@
---
title: Build apps with Stacks
description: Authenticate users, sign transactions and store data with the Stacks blockchain
images:
large: /images/pages/build-apps.svg
sm: /images/pages/build-apps-sm.svg
---
## Introduction
Apps built with the Stacks blockchain give users control over their digital identities, assets, and data.
Unlike most cloud-based apps, they are "decentralized" since they don't depend on any centralized platform, server, or database to function. Rather, they use the Stacks blockchain to authenticate users and facilitate read and write requests for them without any single point of failure or trust.
Stacks provides three main functions for building apps:
- **Authentication**: Register and sign users in with identities on the Stacks blockchain
- **Transaction signing**: Prompt users to sign and broadcast transactions to the Stacks blockchain
- **Data storage**: Save and retrieve data for users with [Gaia](/build-apps/references/gaia)
All three of these integrations can be used together to create powerful new user experiences that rival or exceed those of traditional apps—all while protecting your users' digital rights.
While integration is possible for any type of app, most of the resources available here are for web developers experienced with JavaScript. See [Hiro developer docs](https://docs.hiro.so) for more information on the available app development libraries for Stacks.
## References
[@page-reference | grid] | /build-apps/references/authentication, /build-apps/references/bns, /build-apps/references/gaia

65
src/pages/de/build-apps/references/authentication.md

@ -0,0 +1,65 @@
---
title: Authentication
description: Register and sign in users with identities on the Stacks blockchain
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Introduction
This guide explains how authentication is performed on the Stacks blockchain.
Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite.
Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](/build-apps/references/bns) and vice versa.
## How it works
The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side.
An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token.
These tokens are are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings.
When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter:
`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...`
When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`.
The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`.
The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions:
1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub
2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage.
3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions.
Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain.
The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/build-apps/references/gaia).
## Key pairs
Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular.
The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed.
### Transit private key
The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response.
The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request.
### Identity address private key
The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator.
This private key signs the authentication response token for an app to indicate that the user approves sign in to that app.
### App private key
The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input.
The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key.

244
src/pages/de/build-apps/references/bns.md

@ -0,0 +1,244 @@
---
title: Blockchain Naming System
description: Binds Stacks usernames to off-chain state
images:
large: /images/nodes.svg
sm: /images/nodes.svg
---
Blockchain Naming System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control.
The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block.
Names in BNS have three properties:
- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state.
- **Names are human-meaningful.** Each name is chosen by its creator.
- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys.
The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network.
The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions.
## Motivation behind naming systems
We rely on naming systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's naming system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key.
What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be.
- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to.
- **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes.
- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states.
- **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene.
- In PGP, names are key IDs. They are are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference.
- **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system.
BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more:
- Build domain name services where hostnames can't be hijacked.
- Build social media platforms where user names can't be stolen by phishers.
- Build version control systems where repository branches do not conflict.
- Build public-key infrastructure where it's easy for users to discover and remember each other's keys.
## Organization of BNS
BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming:
- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators.
- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already.
- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules.
A feature comparison matrix summarizing the similarities and differences between these name objects is presented below:
| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** |
| -------------------------------------- | -------------- | ------------- | ------------------ |
| Globally unique | X | X | X |
| Human-meaningful | X | X | X |
| Owned by a private key | | X | X |
| Anyone can create | X | X | [1] |
| Owner can update | | X | [1] |
| State hosted on-chain | X | X | |
| State hosted off-chain | | X | X |
| Behavior controlled by consensus rules | X | X | |
| May have an expiration date | | X | |
[1] Requires the cooperation of a BNS name owner to broadcast its transactions
## Namespaces
Namespaces are the top-level naming objects in BNS.
They control a few properties about the names within them:
- How expensive they are to register
- How long they last before they have to be renewed
- Who (if anyone) receives the name registration fees
- Who is allowed to seed the namespace with its initial names.
At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered unspendable (the intention is to discourage ID squatters).
Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever.
However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`).
Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`.
## Subdomains
BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth.
BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations.
This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored.
For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file:
```bash
$TTL 3600
1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg=="
2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK"
10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo="
31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg=="
359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo="
30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg=="
onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg=="
10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo="
36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg=="
_http._tcp URI 10 1 "https://dotpodcast.co/"
```
Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to:
```json
{
"address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH",
"blockchain": "bitcoin",
"last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339",
"status": "registered_subdomain",
"zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3",
"zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n"
}
```
This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`.
### Subdomain Lifecycle
Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`.
The lifecycle of a subdomain and its operations is shown in Figure 2.
```
subdomain subdomain subdomain
creation update transfer
+----------------+ +----------------+ +----------------+
| cicero | | cicero | | cicero |
| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." |
| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ...
| seqn=0 | | seqn=1 | | seqn=2 |
| | | sig="xxxx" | | sig="xxxx" |
+----------------+ +----------------+ +----------------+
| | |
| off-chain | |
~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ...
| on-chain | |
V V (zone file hash ) V
+----------------+ +----------------+ +----------------+
| res_publica.id | | jude.id | | res_publica.id |
| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ...
+----------------+ +----------------+ +----------------+
blockchain blockchain blockchain
block block block
Figure 2: Subdomain lifetime with respect to on-chain name operations .A new
subdomain operation will only be accepted if it has a later "sequence=" number,
and a valid signature in "sig=" over the transaction body .The "sig=" field
includes both the public key and signature, and the public key must hash to
the previous subdomain operation's "addr=" field.
The subdomain-creation and subdomain-transfer transactions for
"cicero.res_publica.id" are broadcast by the owner of "res_publica.id."
However, any on-chain name ("jude.id" in this case) can broadcast a subdomain
update for "cicero.res_publica.id."
```
Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include:
- The next sequence number
- The public key that hashes to the previous subdomain transaction's address
- A signature from the corresponding private key over the entire subdomain operation.
If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored.
Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain.
### Subdomain Creation and Management
Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular:
- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`.
- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key.
- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files.
- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`.
That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner.
Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network.
If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it.
### Subdomain Registrars
Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin.
We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application.
# BNS and DID Standards
BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs).
Each name in BNS has an associated DID. The DID format for BNS is:
```bash
did:stack:v0:{address}-{index}
```
Where:
- `{address}` is an on-chain public key hash (for example a Bitcoin address).
- `{index}` refers to the `nth` name this address created.
For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`.
As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`).
The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not.
Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name:
- The name must exist
- The name's zone file hash must be the hash of a well-formed DNS zone file
- The DNS zone file must be present in the Stacks node's data.
- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token
- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name
Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do.
A RESTful API is under development.
## DID Encoding for Subdomains
Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take.
- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses).
- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively.
The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63).

92
src/pages/de/build-apps/references/gaia.md

@ -0,0 +1,92 @@
---
title: Gaia
description: Decentralized storage architecture for off-chain data
images:
large: /images/pages/data-storage.svg
sm: /images/pages/data-storage-sm.svg
---
## Introduction
Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia.
Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage.
Storing data off of the blockchain ensures that Stacks applications can provide users with high performance and high availability for data reads and writes without introducing central trust parties.
## Understand Gaia in the Stacks architecture
The following diagram depicts the Stacks architecture and Gaia's place in it:
![Stacks Architecture](/images/architecture.png)
Blockchains require consensus among large numbers of people, so they can be slow. Additionally, a blockchain is not designed to hold a lot of data. This means using a blockchain for every bit of data a user might write and store is expensive. For example, imagine if an application were storing every tweet in the chain.
The Stacks blockchain addresses performance problems using a layered approach. The base layer consists of the Stacks blockchain and the Blockchain Naming System (BNS). The blockchain governs ownership of identities in the Stacks network. Identities can be names such as domain names, usernames, or application names.
When an identity is created, its creation is recorded in the Stacks blockchain. Identities make up the primary data stored into the Stacks blockchain. These identities correspond to routing data in the OSI stack. The routing data is stored in the Atlas Peer Network, the second layer. Every core node that joins the Stacks Network is able to obtain an entire copy of this routing data. Stacks uses the routing data to associate identities (domain names, user names, and application names) with a particular storage location in the final layer, the Gaia Storage System.
A Gaia Storage System consists of a _hub service_ and storage resource on a cloud software provider. The storage provider can be any commercial provider such as Azure, DigitalOcean, Amazon EC2, and so forth. Typically the compute resource and the storage resource reside same cloud vendor, though this is not a requirement. Gaia currently has driver support for S3, Azure Blob Storage, Google Cloud Platform and local disk, but the driver model allows for other backend support as well.
Gaia stores data as a simple key-value store. When an identity is created, a corresponding data store is associated with that identity on Gaia. When a user logs into a dApp, the authentication process gives the application the URL of a Gaia hub, which then writes to storage on behalf of that user.
The Stacks blockchain stores only identity data. Data created by the actions of an identity is stored in a Gaia Storage System. Each user has profile data. When a user interacts with a decentralized dApp that application stores application data on behalf of the user. Because Gaia stores user and application data off the blockchain, a Stacks DApp is typically more performant than DApps created on other blockchains.
## User control or how is Gaia decentralized?
A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider.
![Gaiastorage](/images/gaia-storage.png)
Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data.
The control of user data lies in the way that user data is accessed. When an application fetches a file `data.txt` for a given user `alice.id`, the lookup will follow these steps:
1. Fetch the `zonefile` for `alice.id`.
2. Read her profile URL from her `zonefile`.
3. Fetch Alice's profile.
4. _Verify_ that the profile is signed by `alice.id`'s key
5. Find the read-only url out of the profile's `appsMeta` section (e.g. `https://example-app.gaia.alice.org`).
6. Fetch the file from `https://example-app.gaia.alice.org/data.txt`.
Because `alice.id` has access to her [zonefile](https://docs.stacks.co/references/bns-contract#name-update), she can change where her profile is stored. For example, she may do this if the current profile's service provider or storage is compromised. To change where her profile is stored, she changes her Gaia hub URL to another Gaia hub URL. If a user has sufficient compute and storage resources, a user may run their own Gaia Storage System and bypass a commercial Gaia hub provider all together.
~> Users with existing identities cannot yet migrate their data from one hub to another.
Applications writing directly on behalf of `alice.id` do not need to perform a lookup. Instead, the [Stacks authentication flow](http://blockstack.github.io/stacks.js/index.html) provides Alice's chosen gaia hub URL to the application. This authentication flow _is also_ within Alice's control because Alice's wallet _must_ generate the authentication response.
## Understand data storage
A Gaia hub stores the written data _exactly_ as given. It offers minimal guarantees about the data. It does not ensure that data is validly formatted, contains valid signatures, or is encrypted. Rather, the design philosophy is that these concerns are client-side concerns.
Client libraries (such as [`Stacks.js`](https://stacks.js.org/)) are capable of providing these guarantees. A liberal definition of the [end-to-end principle](https://en.wikipedia.org/wiki/End-to-end_principle) guides this design decision.
When an application writes to a Gaia hub, an authentication token, key, and the data are passed to the Gaia hub.
![Gaia writes](/images/gaia-writes.png)
The token ensures the app has the authorization to write to the hub on the user's behalf.
## Gaia versus other storage systems
Here's how Gaia stacks up against other decentralized storage systems. Features that are common to all storage systems are omitted for brevity.
| Features | [Gaia](https://github.com/stacks-network/gaia) | [Sia](https://sia.tech/) | [Storj](https://storj.io/) | [IPFS](https://ipfs.io/) | [DAT](https://datproject.org/) | [SSB](https://www.scuttlebutt.nz/) |
| ------------------------------------------ | ---------------------------------------------- | ------------------------ | -------------------------- | ------------------------ | ------------------------------ | ---------------------------------- |
| User controls where data is hosted | X | | | | | |
| Data can be viewed in a normal Web browser | X | | | X | | |
| Data is read/write | X | | | | X | X |
| Data can be deleted | X | | | | X | X |
| Data can be listed | X | X | X | | X | X |
| Deleted data space is reclaimed | X | X | X | X | | |
| Data lookups have predictable performance | X | | X | | | |
| Writes permission can be delegated | X | | | | | |
| Listing permission can be delegated | X | | | | | |
| Supports multiple backends natively | X | | X | | | |
| Data is globally addressable | X | X | X | X | X | |
| Needs a cryptocurrency to work | | X | X | | | |
| Data is content-addressed | | X | X | X | X | X |
## Deploy your GAIA hub
Steps to deploy your own GAIA hub can be found [here](https://github.com/stacks-network/gaia/blob/master/deploy/README.md)

268
src/pages/de/contributing.md

@ -0,0 +1,268 @@
---
title: How to contribute
description: Learn how this site is built, and how you could contribute to it.
icon: BlockstackIcon
images:
large: /images/contribute.svg
sm: /images/contribute.svg
---
## Introduction
Welcome. Thank you for your interest in contributing and helping make these docs as good as they can be. This page will outline how this site is built, its general structure, getting it running locally, and some helpful tips for using all of its features.
## Next.js, MDX, Markdown
This docs site is built with [Next.js](https://github.com/vercel/next.js) and uses something called [MDX](https://mdxjs.com/). Next.js is a framework built on top of React, and MDX is a tool that enables writing React code (JSX) within standard Markdown files. In addition to being able to write JSX in Markdown, it allows the application to render out all of the Markdown content with React components. This means that we are able to do some pretty complex things while a contributor only has to know how to write Markdown.
-> **Don't know what Markdown is?** Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/) for learning it.
## Getting started
To get started you have two options:
1. using web IDE Gitpod in your browser.
2. working locally.
### Working in browser
The web IDE gitpod provides an environment to contibute directly from within your browser.
To get started, you only have to a github account and open the link [https://gitpod.io/#https://github.com/stacks-network/docs](https://gitpod.io/#https://github.com/stacks-network/docs) in your browser.
### Working Locally
When workin locally with the site, a few things are needed:
- Familiarity with `git`, GitHub, and the command line. [Read more here.](https://docs.github.com/en/github/getting-started-with-github/quickstart)
- [`node` + `npm`,](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) and [`yarn` installed](https://yarnpkg.com/getting-started/install) on your machine.
- Some kind of code editor, such as VSCode, Sublime, or WebStorm.
-> This project requires at least Node version 12
### Working with GitHub
All of the code for this site is open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). Before you start editing anything, you will need to fork the repo so that you can have your own copy of the code under your GitHub profile. On the [repository's page](https://github.com/stacks-network/docs), you should be able to see a button in the upper right of the screen that says "Fork." [You can read about Forking here.](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo)
This is a generalized workflow for contributing to these docs:
- Clone your fork to your local machine with this command `git clone git@github.com:<YOUR_USERNAME>/docs.git stacks_docs`
- Enter your project folder `cd stacks_docs`
- Create a branch `git checkout -b feat/my-feature-branch`.
- Run the command `yarn` to install all of the dependencies.
- Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`.
- Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`.
- Visit GitHub and make your pull request.
### Running the site locally
Once you have the project on your computer and the dependencies have been installed via the `yarn` command, you can run `yarn dev` and it should give you a message such as:
```bash
yarn dev
```
```bash
yarn run v1.22.17
$ yarn clean:build-files && next dev
$ rimraf .next && rimraf .cache
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
warn - You have enabled experimental feature(s).
warn - Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use them at your own risk.
info - Disabled SWC as replacement for Babel because of custom Babel configuration "babel.config.js" https://nextjs.org/docs/messages/swc-disabled
info - automatically enabled Fast Refresh for 1 custom loader
info - Using external babel configuration from /home/alejandro/stacks-network_docs/babel.config.js
event - compiled client and server successfully in 13.5s (680 modules)
```
The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000).
## Project structure
### Pages
If you are interested in only adding new documentation content to the site, the files that will be important to you are located within `./src/pages/*`:
```bash showLineNumbers highlight=11
stacks_docs/
.github/
lib/
node_modules/
public/
src/
_data/
_includes/
common/
components/
pages/
types/
```
The routing for this site is file based, meaning if you created a folder within `/pages` named `clarity` and a then file named `overview.md`, you would be able to navigate to `http://localhost:3000/clarity/overview` and you would see whatever content is in that markdown file.
### Frontmatter
Frontmatter is the top part of any markdown document that is written in a language called [YAML](https://yaml.org/). It looks like this:
```yaml
---
title: This is my page title
description: A short, concise sentence describing what is on this page
---
```
Frontmatter gives us the ability to define some things within a page that the site can use, such as a page title or page description. When adding any new page, please include a `title` and `description`.
-> **Did you know?** The term _Frontmatter_ comes from the section in a book at the beginning detailing things like: publisher’s name and address, copyright information, table of contents, etc.
### Dynamic sidebar
The sidebar navigation is generated in a partially dynamic way. The application searches through a list of paths and parses the markdown to get some information about the page, such as the title and headings contained within the page.
#### Adding a new route
If you are adding a new route, you have to add your route to a section contained within this file: `src/common/navigation.yaml`
```bash showLineNumbers highlight=11
sections:
- pages:
- path: /
- path: /understand-stacks
pages:
- path: /overview
- path: /testnet
- path: /proof-of-transfer
- path: /mining
- path: /accounts
- path: /transactions
- path: /network
- path: /stacking
- path: /command-line-interface
- path: /local-development
- path: /technical-specs
- path: /stacks-blockchain-api
sections:
- title: Tutorials
pages:
- path: /managing-accounts
- path: /sending-tokens
- path: /running-testnet-node
- path: /integrate-stacking
- path: /stacking-using-CLI
```
Adding a new route requires to add a new `path`.
The script will process that file and pull out the title from the frontmatter of the document.
### Non-standard pages
There are a few pages within these docs that are non-standard markdown pages. This means they are using some kind of external data as their source, such as the [Clarity Reference page](/references/language-overview), or the [Stacks CLI page](https://docs.hiro.so/references/stacks-cli). These pages are using a function of Next.js called [`getStaticProps`](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) which allows us to fetch external data at runtime and use it in some way within our pages.
## Tips and tricks
### Style checks
We use the [Google Developer documentation style guides](https://developers.google.com/style/) in this project. Make sure to install [vale](https://github.com/errata-ai/vale) and run the style checks before you create a PR:
```bash
yarn check:style
```
### Use Conventional Commits
We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please.
### Always use Markdown when possible
It's possible to write standard HTML when writing in Markdown, but that should be avoided at all costs. We use `remark` to processes all Markdown, giving us things like automatically opening all external links in new windows, and adding IDs to headers. When we write things in HTML, such as a link or image, we don't get the benefit of the remark plugins as consistently as we would if we stuck to standar Markdown.
### Code blocks
The site uses `react-prism-renderer` and `prismjs` to add syntax highlighting to all of our code. You can see a full list of [languages supported here](https://github.com/PrismJS/prism/tree/master/components). We have a custom language definition for `clarity`, our smart contracting language located here. To add a new language, see this file: [`components/codeblock/index.tsx`](#).
To write a code block, you need to wrap your code in ` ```language `, and end your code block with ` ``` `. Here is an example of ` ```clarity `.
```clarity
(define-data-var counter int 0)
(define-public (get-counter)
(ok (var-get counter)))
```
#### Line highlighting
You can pass some extra data to tell the component to highlight specific lines:
` ```clarity highlight=1,4-6,13-17,28-32 `
Which will render:
```clarity highlight=1,4-6,13-17,28-32
(define-constant sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)
(define-constant recipient 'SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G)
(define-fungible-token novel-token-19)
(begin (ft-mint? novel-token-19 u12 sender))
(begin (ft-transfer? novel-token-19 u2 sender recipient))
(define-non-fungible-token hello-nft uint)
(begin (nft-mint? hello-nft u1 sender))
(begin (nft-mint? hello-nft u2 sender))
(begin (nft-transfer? hello-nft u1 sender recipient))
(define-public (test-emit-event)
(begin
(print "Event. Hello world")
(ok u1)))
(begin (test-emit-event))
(define-public (test-event-types)
(begin
(unwrap-panic (ft-mint? novel-token-19 u3 recipient))
(unwrap-panic (nft-mint? hello-nft u2 recipient))
(unwrap-panic (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR))
(unwrap-panic (stx-burn? u20 tx-sender))
(ok u1)))
(define-map store ((key (buff 32))) ((value (buff 32))))
(define-public (get-value (key (buff 32)))
(begin
(match (map-get? store ((key key)))
entry (ok (get value entry))
(err 0))))
(define-public (set-value (key (buff 32)) (value (buff 32)))
(begin
(map-set store ((key key)) ((value value)))
(ok u1)))
```
### Alerts
We use another remark plugin to generate certain kinds of alerts inline in our documentation.
```md
> This is a standard blockquote (non-alert).
-> This will be a standard note style alert.
=> This will be a success style alert.
~> This will be a warning style alert
!> This will be a danger style alert
```
Which renders:
> This is a standard blockquote (non-alert).
-> This will be a standard note style alert.
=> This will be a success style alert.
~> This will be a warning style alert
!> This will be a danger style alert

18
src/pages/de/index.md

@ -0,0 +1,18 @@
---
title: Stacks documentation
description: Learn about Stacks mining, the STX token, and the Clarity smart contract language
---
-> Content related to developer tools and app development has recently moved to [docs.hiro.so](https://docs.hiro.so/). For more information on the content move, see [this post](https://forum.stacks.org/t/the-evolution-of-the-stacks-documentation-and-a-new-hiro-docs-site/12343) on the Stacks forum.
## Understand Stacks
[@page-reference | grid] | /understand-stacks/overview, /understand-stacks/proof-of-transfer, /understand-stacks/testnet
## Write smart contracts
[@page-reference | grid] | /write-smart-contracts/overview, /write-smart-contracts/tokens
## Start mining
[@page-reference | grid] | /start-mining/mainnet, /start-mining/testnet

24
src/pages/de/references/bns-contract.md

@ -0,0 +1,24 @@
---
title: BNS Contract
description: See a detailed list of all functions and error codes of the BNS contract.
---
export { convertBNSRefToMdx as getStaticProps } from '@common/data/bns-ref'; import { BNSErrorcodeReference, BNSFunctionReference } from '@components/bns-ref';
## Introduction
The [Blockchain Naming System (BNS)](/build-apps/references/bns) is implemented as a smart contract using Clarity.
Below is a list of public and read-only functions as well as error codes that can be returned by those methods.
## Public functions
<BNSFunctionReference {...props.mdx.publicFunctions} />
## Read-only functions
<BNSFunctionReference {...props.mdx.readonlyFunctions} />
## Error codes
<BNSErrorcodeReference {...props.mdx.errorCodes} />

51
src/pages/de/references/deploy-tips.md

@ -0,0 +1,51 @@
---
title: Deploy tips
description: Learn some common methods for deploying your application.
---
## Introduction
Stacks applications are web applications that authenticate users with Stacks Auth and store data with Gaia. Both of these technologies can be accessed on the client side. As such, Stacks apps tend to be simple in design and operation, since in many cases, they don’t have to host anything besides the application’s assets.
## Where to deploy your application
Before users can interact with your application, you must deploy it on a server that is accessible over the internet. Deploying requires that you:
- Configure or customize the files in the `public` directory.
- Build your application site for deployment.
- Copy your generated application files to your production server.
If you first populated your application with the Stacks application generator, your application contains the starting blocks for configuring, building, and deploying your app. For example, the React template builds out a scaffolding with the following building blocks.
| File or Directory | Description |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| node_modules/react-scripts | A set of scripts for that helps you kick off React projects without configuring, so you do not have to set up your project by yourself. |
| package.json | Contains a scripts section that includes a reference to the react-scripts, which are a dependency. This script creates a build directory containing your files for deployment. |
| public/favicon.ico | An example shortcut icon. |
| public/index.html | An entry page for an application. |
| public/manifest.json | A JSON file that describes your web application to the browser. |
| cors | Contains example deployment files for cross-origin request configuration. |
If you use the generator to build JavasScript or Vue scaffolding, your project configuration files will be different.
Regardless of which scaffolding you use, you must customize and extend this basic scaffolding as needed by your application. For example, you may want to add more properties to the `manifest.json` file. Since every application is different, Stacks Auth cannot give you specific instructions on how to do this. The steps you take are specific to your application.
## Stacks Authentication and deployment
When your application authenticates users with Stacks, the Stacks Wallet at on URL requests a resource (the app manifest) from your DApp. A request for a resource outside of the origin (the Stacks Wallet) is called as a _cross-origin request_(CORs). Getting data in this manner can be risky, so you must configure your website security to allow interactions across origins.
You can think of CORS interactions as an apartment building with Security. For example, if you need to borrow a ladder, you could ask a neighbor in your building who has one. Security would likely not have a problem with this request (that is, same-origin, your building). If you needed a particular tool, however, and you ordered it delivered from an online hardware store (that is, cross-origin, another site), Security may request identification before allowing the delivery man into the apartment building. (Credit: Codecademy)
The way you configure CORs depends on which company you use to host your web application. The application generator adds a `cors` directory to your application scaffolding. This directory contains files for Netlify (`_headers` and `_redirects`) as well as one for Firebase (`firebase.json`). The configurations in the `cors` directory make your application's `manifest.json` file accessible to other applications (for example, to the Stacks Browser). If you are deploying to a service other than Netlify or Firebase, you must configure CORS on that service to include the following headers when serving `manifest.json`:
````html
Access-Control-Allow-Origin: * Access-Control-Allow-Headers: "X-Requested-With, Content-Type,
Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding" Access-Control-Allow-Methods:
"POST, GET, OPTIONS, DELETE, PUT"```
````
Consult the documentation for your hosting service to learn how to configure CORS on that service.
## Deployment and Radiks
If you are deploying a Stacks application that uses Radiks, your deployment includes a server and a database component. You must take this into account when deploying your application. You may want to choose a service such as Heroku or Digital Ocean if your app uses Radiks.

24
src/pages/de/references/faqs.md

@ -0,0 +1,24 @@
---
title: FAQs
description: Find answers related to the Stacks ecosystem.
---
## General Information
Learn more about the user-owned internet on Bitcoin and the Stacks ecosystem on [stacks.co](https://stacks.co).
## Apps and Smart Contracts
Developers, get started building apps and contracts on the [developer page at stacks.co](https://www.stacks.co/developers).
## Stacks Network
Learn more about the network behind the user-owned internet on Bitcoin in the [Understand Stacks chapter](/understand-stacks/overview) in the docs.
## Stacks Token
Stacks fuel apps and smart contracts on Bitcoin. Learn more at [stackstoken.com](https://stackstoken.com/faq).
## Stacks Wallet
Download and find resources about the Stacks Wallet by Hiro at [hiro.so](https://www.hiro.so/wallet).

8
src/pages/de/references/glossary.md

@ -0,0 +1,8 @@
---
title: Glossary
description: A comprehensive list of terms used within the ecosystem.
---
export { convertGlossaryToJson as getStaticProps } from '@common/data/glossary'; import { Glossary } from '@components/glossary';
<Glossary data={props.glossary} />

10
src/pages/de/references/language-functions.md

@ -0,0 +1,10 @@
---
title: Functions
description: See a detailed list of all functions for the Clarity language.
---
export { convertClarityRefToMdx as getStaticProps } from '@common/data/clarity-ref'; import { ClarityFunctionReference } from '@components/clarity-ref';
## Function reference
<ClarityFunctionReference {...props.mdx.functions} />

10
src/pages/de/references/language-keywords.md

@ -0,0 +1,10 @@
---
title: Keywords
description: See a detailed list of all keywords for the Clarity language.
---
export { convertClarityRefToMdx as getStaticProps } from '@common/data/clarity-ref'; import { ClarityKeywordReference } from '@components/clarity-ref';
## Keyword reference
<ClarityKeywordReference {...props.mdx.keywords} />

84
src/pages/de/references/language-overview.md

@ -0,0 +1,84 @@
---
title: Overview
description: Overview of the Clarity language constructs
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
export { convertClarityRefToMdx as getStaticProps } from '@common/data/clarity-ref'; import { ClarityKeywordReference, ClarityFunctionReference } from '@components/clarity-ref';
## Clarity Type System
The Clarity language uses a strong static type system. Function arguments and database schemas require specified types, and use of types is checked during contract launch. The type system does _not_ have a universal super type.
## Public Functions
Functions specified via `define-public` statements are _public_ functions and these are the only types of functions which may be called directly through signed blockchain transactions. In addition to being callable directly from a transaction (see the Stacks wire formats for more details on Stacks transactions), public function may be called by other smart contracts.
Public functions _must_ return a `(response ...)` type. This is used by Clarity to determine whether or not to materialize any changes from the execution of the function. If a function returns an `(err ...)` type, and mutations on the blockchain state from executing the function (and any function that it called during execution) will be aborted.
In addition to function defined via `define-public`, contracts may expose read-only functions. These functions, defined via `define-read-only`, are callable by other smart contracts, and may be queryable via public blockchain explorers. These functions _may not_ mutate any blockchain state. Unlike normal public functions, read-only functions may return any type.
## Contract Calls
A smart contract may call functions from other smart contracts using a `(contract-call?)` function.
This function returns a response type result-- the return value of the called smart contract function.
We distinguish 2 different types of `contract-call?`:
### Static dispatch
The callee is a known, invariant contract available on-chain when the caller contract is deployed. In this case, the callee's principal is provided as the first argument, followed by the name of the method and its arguments:
```clarity
(contract-call?
.registrar
register-name
name-to-register)
```
### Dynamic dispatch
The callee is passed as an argument, and typed as a trait reference (`<A>`).
```clarity
(define-public (swap (token-a <can-transfer-tokens>)
(amount-a uint)
(owner-a principal)
(token-b <can-transfer-tokens>)
(amount-b uint)
(owner-b principal)))
(begin
(unwrap! (contract-call? token-a transfer-from? owner-a owner-b amount-a))
(unwrap! (contract-call? token-b transfer-from? owner-b owner-a amount-b))))
```
Traits can either be locally defined:
```clarity
(define-trait can-transfer-tokens (
(transfer-from? (principal principal uint) (response uint)))
```
Or imported from an existing contract:
```clarity
(use-trait can-transfer-tokens
.contract-defining-trait.can-transfer-tokens)
```
Looking at trait conformance, callee contracts have two different paths. They can either be "compatible" with a trait by defining methods matching some of the methods defined in a trait, or explicitely declare conformance using the `impl-trait` statement:
```clarity
(impl-trait .contract-defining-trait.can-transfer-tokens)
```
Explicit conformance should be prefered when adequate. It acts as a safeguard by helping the static analysis system to detect deviations in method signatures before contract deployment.
The following limitations are imposed on contract calls:
1. On static dispatches, callee smart contracts _must_ exist at the time of creation.
2. No cycles may exist in the call graph of a smart contract. This prevents recursion (and re-entrancy bugs). Such structures can be detected with static analysis of the call graph, and will be rejected by the network.
3. `contract-call?` are for inter-contract calls only. Attempts to execute when the caller is also the callee will abort the transaction.

23
src/pages/de/references/language-types.md

@ -0,0 +1,23 @@
---
title: Types
description: See a detailed list of all types for the Clarity language.
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Clarity Type System
The type system contains the following types:
- `{label-0: value-type-0, label-1: value-type-1, ...}` - a group of data values with named fields, aka (_record_)[https://www.cs.cornell.edu/courses/cs312/2004fa/lectures/lecture3.htm].
- `(list max-len entry-type)` - a list of maximum length `max-len`, with entries of type `entry-type`
- `(response ok-type err-type)` - object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior.
- `(optional some-type)` - an option type for objects that can either be `(some value)` or `none`
- `(buff max-len)` := byte buffer of maximum length `max-len`.
- `(string-ascii max-len)` := ASCII string of maximum length `max-len`
- `(string-utf8 max-len)` := UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string")
- `principal` := object representing a principal (whether a contract principal or standard principal).
- `bool` := boolean value (`true` or `false`)
- `int` := signed 128-bit integer
- `uint` := unsigned 128-bit integer

24
src/pages/de/references/stacking-contract.md

@ -0,0 +1,24 @@
---
title: Stacking Contract
description: See a detailed list of all functions and error codes of the Stacking contract.
---
export { convertStackingRefToMdx as getStaticProps } from '@common/data/stacking-ref'; import { StackingErrorcodeReference, StackingFunctionReference } from '@components/stacking-ref';
## Introduction
Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info).
Below is a list of public and read-only functions as well as error codes that can be returned by those methods.
## Public functions
<StackingFunctionReference {...props.mdx.publicFunctions} />
## Read-only functions
<StackingFunctionReference {...props.mdx.readonlyFunctions} />
## Error codes
<StackingErrorcodeReference {...props.mdx.errorCodes} />

513
src/pages/de/references/stacks-node-configuration.md

@ -0,0 +1,513 @@
---
title: Stacks Node Configuration
description: Configuration parameters and options for the stacks-node binary
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Usage
```bash
stacks-node sub-command [--subcommand-option <value>]
```
## Subcommands
-> Note that the `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources.
### mocknet
Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development.
Example:
```bash
stacks-node mocknet
```
### krypton
Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](/understand-stacks/overview#proof-of-transfer-pox).
Example:
```bash
stacks-node krypton
```
### xenon
Start a node that will join and stream blocks from the public xenon testnet.
Example:
```bash
stacks-node xenon
```
### mainnet
Start a node that joins and streams blocks from the public mainnet.
Example:
```bash
stacks-node mainnet
```
### start
Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `xenon` subcommands.
#### Arguments
**--config**: relative or absolute path to the TOML config file. Required.
Example:
```bash
stacks-node start --config=/path/to/config.toml
```
See [Configuration File Options](#configuration-file-options) for more information.
#### version
Displays information about the current version and the release cycle.
Example:
```bash
stacks-node version
```
#### help
Displays a help message.
Example:
```bash
stacks-node help
```
## Configuration File Options
The TOML configuration file has multiple sections under which an option may be placed.
To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf).
### Section: node
Contains various configuration options pertaining to the stacks-node.
Example:
```toml
[node]
rpc_bind = "0.0.0.0:20443"
p2p_bind = "0.0.0.0:20444"
# Enter your private key here
seed = "replace-with-your-private-key"
miner = true
```
#### working_dir (optional)
Absolute path to the directory which the stacks-node will use for storing various data.
Example:
```toml
working_dir = "/root/stacks-node"
```
#### rpc_bind
Address and port stacks-node should bind to for RPC connections.
Example:
```toml
rpc_bind = "0.0.0.0:20443"
```
#### p2p_bind
Address and port stacks-node should bind to for P2P connections.
Example:
```toml
p2p_bind = "0.0.0.0:20444"
```
#### data_url (optional)
Address and port from which the stacks-node will be receiving incoming rpc connections.
Example:
```toml
data_url = "1.2.3.4:20443"
```
#### p2p_address (optional)
Address and port from which the stacks-node will be receiving incoming p2p connections.
Example:
```toml
p2p_address = "1.2.3.4:20444"
```
#### bootstrap_node (optional)
Public key, address, and port stacks-node should use to pull transaction data from when starting.
Example:
```toml
bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@xenon.blockstack.org:20444"
```
#### wait_time_for_microblocks (optional)
The amount of time (in milliseconds) that a node will wait before trying to mine a block, after catching up to the anchored chain tip. This gives the current leader time to broadcast microblocks that will get included in that mined block.
Example:
```toml
wait_time_for_microblocks = 15000
```
#### seed (optional)
The private key to use for mining. Only needed if `miner` is set to `true`.
[See this page for information on how to generate a private key.](/start-mining)
Example:
```toml
seed = "replace-with-your-private-key"
```
#### local_peer_seed (optional)
The private key to use for signing P2P messages in the networking stack. It differentiates network peers and is used even by non-mining nodes.
[See this page for information on how to generate a private key.](/start-mining)
Example:
```toml
local_peer_seed = "replace-with-your-private-key"
```
#### miner (optional)
Determines whether the stacks-node is running a follower (`false`) or a miner (`true`). Defaults to `false` if omitted.
[See this page for information on how to run a miner.](/start-mining)
Example:
```toml
miner = true
```
#### mine_microblocks (optional)
Determines whether the stacks-node will mine microblocks. Will only take effect if `miner` is set to `true`.
[See this page for information on how to run a miner.](/start-mining)
Example:
```toml
mine_microblocks = true
```
#### prometheus_bind (optional)
Address and port stacks-node should open for Prometheus metrics collection.
Example:
```toml
prometheus_bind = "0.0.0.0:9153"
```
### Section: events_observer (optional)
Contains options for watching events emitted by a local [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service.
-> This section can be repeated multiple times.
Example:
```toml
[[events_observer]]
endpoint = "address-to-my-local.stacks-node-api.com:3700"
retry_count = 255
events_keys = ["*"]
```
#### endpoint
Address and port to a stacks-node-api to watch for events.
Example:
```toml
endpoint = "address-to-my-local.stacks-node-api.com:3700"
```
#### retry_count
Number of times to retry sending events to the endpoint before failing.
Example:
```toml
retry_count = 255
```
#### events_keys
Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events.
Examples:
```toml
events_keys = ["*"]
```
```toml
events_keys = [
"STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.store::print",
"STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.contract.ft-token",
"STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.contract.nft-token",
"stx"
]
```
### Section: connection_options (optional)
Specifies configuration options for others connecting to the stacks node.
Example:
```toml
[connection_options]
public_ip_address = "1.2.3.4:20444"
download_interval = 60
walk_interval = 30
```
#### public_ip_address
The advertised public IP of this stacks-node.
Example:
```toml
public_ip_address = "1.2.3.4:20444"
```
#### download_interval
Time (in seconds) between attempts to download blocks.
Example:
```toml
download_interval = 60
```
#### walk_interval
Time (in seconds) between attempts to walk the neighborhood.
Example:
```toml
walk_interval = 30
```
#### read_only_call_limit_read_length
Total number of bytes allowed to be read by an individual read-only function call.
Example:
```toml
read_only_call_limit_read_length = 100000
```
#### read_only_call_limit_read_count
Total number of independent read operations permitted for an individual read-only function call.
Example:
```toml
read_only_call_limit_read_count = 30
```
#### read_only_call_limit_runtime
[Runtime cost](https://github.com/stacksgov/sips/blob/2d3fd9bf8da7a04f588d90ff6252173d7609d7bf/sips/sip-006/sip-006-runtime-cost-assessment.md#introduction) limit for an individual read-only function call.
Example:
```toml
read_only_call_limit_runtime = 1000000000
```
### Section: burnchain
This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC).
Example:
```toml
[burnchain]
chain = "bitcoin"
mode = "mainnet"
peer_host = "your.bitcoind.node.org"
rpc_port = 8332
peer_port = 8333
```
#### chain
The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `"bitcoin"`.
Example:
```toml
chain = "bitcoin"
```
#### mode
The profile or test phase of which to run stacks-node. Valid values are `"mocknet"`, `"helium"`, `"neon"`, `"argon"`, `"krypton"`, `"xenon"`.
Example:
```toml
mode = "xenon"
```
#### peer_host
Domain name of the host running the backend Bitcoin blockchain. It's required to either run a personal Bitcoin node locally, or to use a publicly hosted Bitcoin node.
Example:
```toml
peer_host = "your.bitcoind.node.org"
```
#### rpc_port
peer_host's port stacks-node will connect to for RPC connections.
Example:
```toml
rpc_port = 8332
```
#### peer_port
peer_host's port stacks-node will connect to for P2P connections.
Example:
```toml
peer_port = 8333
```
#### burn_fee_cap (optional)
Maximum amount (in Satoshis) of "burn commitment" to broadcast for the next block's leader election.
Example:
```toml
burn_fee_cap = 30000
```
#### satoshis_per_byte (optional)
Amount (in Satoshis) per [virtual byte](https://en.bitcoin.it/wiki/Weight_units). This is used to compute the transaction fees.
Example:
```toml
satoshis_per_byte = 50
```
So total transaction cost would be `(estimated_tx_size * satoshis_per_byte) + burn_fee_cap`.
#### commit_anchor_block_within (optional)
Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `"helium"`.
Example:
```toml
commit_anchor_block_within = 10000
```
### Section: ustx_balance (testnet/regtest only)
This section contains configuration options pertaining to the genesis block allocation for an address in micro-STX. If a user changes these values, their node may be in conflict with other nodes on the network and find themselves unable to sync with other nodes.
-> This section can repeat multiple times, and thus is in double-brackets. Each section can define only one address. This section is ignored if running a node on mainnet.
Example:
```toml
[[ustx_balance]]
address = "STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6"
amount = 10000000000000000
[[ustx_balance]]
address = "ST11NJTTKGVT6D1HY4NJRVQWMQM7TVAR091EJ8P2Y"
amount = 10000000000000000
[[ustx_balance]]
address = "ST1HB1T8WRNBYB0Y3T7WXZS38NKKPTBR3EG9EPJKR"
amount = 10000000000000000
[[ustx_balance]]
address = "STRYYQQ9M8KAF4NS7WNZQYY59X93XEKR31JP64CP"
amount = 10000000000000000
```
#### address
Address which maintains a micro-STX balance.
Example:
```toml
address = "STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6"
```
#### amount
The balance of micro-STX given to the address at the start of the node.
Example:
```toml
amount = 10000000000000000
```

352
src/pages/de/start-mining/mainnet.md

@ -0,0 +1,352 @@
---
title: Mine mainnet Stacks tokens
description: Set up and run a miner on the Stacks 2.0 mainnet
icon: MainnetIcon
experience: beginners
duration: 10 minutes
tags:
- tutorial
images:
large: /images/pages/start-mining.svg
sm: /images/pages/start-mining-sm.svg
---
## Introduction
Make sure you've followed the [Running mainnet node](/understand-stacks/running-mainnet-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet.
If you're interested in mining on the testnet, you can find instructions on how to do that here:
[@page-reference | inline] | /start-mining/testnet
If you want to learn more about the technical details of mining, please review the mining guide:
[@page-reference | inline] | /understand-stacks/mining
## Running bitcoind locally
To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements)
First, download the bitcoind software for your platform from https://bitcoin.org/en/download.
Next, start bitcoind with the following configuration:
```toml
server=1
rpcuser=your-bitcoind-username
rpcpassword=your-bitcoind-password
txindex=0
listen=1
rpcserialversion=0
maxorphantx=1
banscore=1
bind=0.0.0.0:8333
rpcbind=0.0.0.0:8332
rpcport=8332
```
Finally, start bitcoind as follows:
```bash
bitcoind -conf=path/to/bitcoin.conf
```
It may take a few days for the node to synchronize with the Bitcoin mainnet.
## Running a miner
First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command.
```bash
npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt
```
After this runs, you should see some JSON in the new `keychain.txt` file that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
**Don't lose this information** - we'll need to use the `privateKey` field later on.
The above BTC address will then need to be imported into the BTC network.
```bash
bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress <btcAddress from JSON above>
```
Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
# Enter your private key here
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on mainnet, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file.
To run your miner, run this in the command line:
```bash
stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml
```
Your node should start. It will take some time to sync, and then your miner will be running.
### Creating an optimized binary
The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run:
```bash
cd testnet/stacks-node
cargo build --release --bin stacks-node
```
The above code will compile an optimized binary. To use it, run:
```bash
cd ../..
./target/release/stacks-node start --config=./mainnet-miner-conf.toml
```
For a full reference of subcommands and configuration options used by `stacks-node`, please see this page.
[@page-reference | inline] | /references/stacks-node-configuration
To read more about the technical details of mining on the Stacks 2.0 network, have a look at the minig guide:
[@page-reference | inline] | /understand-stacks/mining
### Enable debug logging
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
STACKS_LOG_DEBUG=1 stacks-node mainnet
```
## Running a miner in Windows
### Prerequisites
Make sure you've followed the [Running the mainnet node on Windows](/understand-stacks/running-mainnet-node#running-the-mainnet-node-on-windows) tutorial and [Running itcoind locally](#running-bitcoind-locally) section above before starting this tutorial.
### Generate keychain and get mainnet tokens in Windows
To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command.
Generate a keychain:
```bash
npm install --global @stacks/cli
stx make_keychain > cli_keychain.json
type cli_keychain.json
```
After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
-> Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details
The above BTC address will then need to be imported into the BTC network.
```bash
bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress <btcAddress from JSON above>
```
Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
### Update configuration file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
# Enter your private key here
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on mainnet, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Run the miner
To start your miner, run this in the command line:
```bash
stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml
```
-> **Note** : While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. ![Windows Defender](/images/windows-defender.png)
Your node should start. It will take some time to sync, and then your miner will be running.
### Enable debug logging in Windows
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
set RUST_BACKTRACE=full;
set STACKS_LOG_DEBUG=1;
stacks-node start --config=mainnet-miner-conf.toml
```
## Optional: Running with Docker
Alternatively, you can run the mainnet node with Docker.
-> Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine.
### Generate keychain and get tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null
```
We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
### Update configuration file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
# Enter your private key here
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on mainnet, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Start the miner
-> The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled
```bash
docker run -d \
--name stacks_miner \
--rm \
--network host \
-e RUST_BACKTRACE="full" \
-e STACKS_LOG_DEBUG="1" \
-v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain:latest \
/bin/stacks-node start --config /src/stacks-node/mainnet-miner-conf.toml
```
You can review the node logs with this command:
```bash
docker logs -f stacks_miner
```
## Optional: Running in Kubernetes with Helm
In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).
Ensure you have the following prerequisites installed on your machine:
- [Docker](https://docs.docker.com/get-docker/)
- [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster)
- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)
- [helm](https://helm.sh/docs/intro/install/)
### Generate keychain and get some tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null
```
We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
### Install the chart and run the miner
To install the chart with the release name `my-release` and run the node as a miner:
```bash
minikube start # Only run this if standing up a local Kubernetes cluster
helm repo add blockstack https://charts.blockstack.xyz
helm install my-release blockstack/stacks-blockchain \
--set config.node.miner=true \
--set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \
--set config.burnchain.mode="mainnet"
```
You can review the node logs with this command:
```bash
kubectl logs -l app.kubernetes.io/name=stacks-blockchain
```
For more information on the Helm chart and configuration options, please refer to the [chart's homepage](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).

343
src/pages/de/start-mining/testnet.md

@ -0,0 +1,343 @@
---
title: Mine testnet Stacks tokens
description: Set up and run a miner on the Stacks 2.0 testnet
icon: TestnetIcon
experience: beginners
duration: 10 minutes
tags:
- tutorial
images:
large: /images/pages/start-mining.svg
sm: /images/pages/start-mining-sm.svg
---
## Introduction
Make sure you've followed the [Running testnet node](/understand-stacks/running-testnet-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet.
If you want to learn more about the technical details of mining, please review the mining guide:
[@page-reference | inline] | /understand-stacks/mining
## Running bitcoind locally
To participate as a miner on Xenon, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements)
First, download the bitcoind software for your platform from https://bitcoin.org/en/download.
Next, start bitcoind with the following configuration:
```toml
server=1
rpcuser=your-bitcoind-username
rpcpassword=your-bitcoind-password
testnet=1
txindex=0
listen=1
rpcserialversion=0
maxorphantx=1
banscore=1
[test]
bind=0.0.0.0:18333
rpcbind=0.0.0.0:18332
rpcport=18332
```
Finally, start bitcoind as follows:
```bash
bitcoind -conf=path/to/bitcoin.conf
```
It may take a few hours for the node to synchronize with the Bitcoin testnet.
## Running a miner
First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command, and pass `-t` to indicate that we want a testnet keychain.
```bash
npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt
```
After this runs, you should see some JSON in the new `keychain.txt` file that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
**Don't lose this information** - we'll need to use the `privateKey` field later on.
The above BTC address will then need to be imported into the BTC testnet network.
```bash
bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress <btcAddress from JSON above>
```
Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address.
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on Xenon, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file.
To run your miner, run this in the command line:
```bash
stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml
```
Your node should start. It will take some time to sync, and then your miner will be running.
### Creating an optimized binary
The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run:
```bash
cd testnet/stacks-node
cargo build --release --bin stacks-node
```
The above code will compile an optimized binary. To use it, run:
```bash
cd ../..
./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml
```
For a full reference of subcommands and configuration options used by `stacks-node`, please see this page.
[@page-reference | inline] | /references/stacks-node-configuration
To read more about the technical details of mining on the Stacks 2.0 network, have a look at the minig guide:
[@page-reference | inline] | /understand-stacks/mining
### Enable debug logging
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
STACKS_LOG_DEBUG=1 stacks-node xenon
```
## Running a miner in Windows
### Prerequisites
Make sure you've followed the [Running the testnet node on Windows](/understand-stacks/running-testnet-node#running-the-testnet-node-on-windows) tutorial before starting this tutorial.
### Generate keychain and get testnet tokens in Windows
To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain.
Generate a keychain:
```bash
npm install --global @stacks/cli
stx make_keychain -t > cli_keychain.json
type cli_keychain.json
```
After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
-> Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details
Request BTC from faucet:
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address.
### Update configuration file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on Xenon, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Run the miner
To start your miner, run this in the command line:
```bash
stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml
```
-> **Note** : While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. ![Windows Defender](/images/windows-defender.png)
Your node should start. It will take some time to sync, and then your miner will be running.
### Enable debug logging in Windows
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
set RUST_BACKTRACE=full;
set STACKS_LOG_DEBUG=1;
stacks-node start --config=testnet-miner-conf.toml
```
## Optional: Running with Docker
Alternatively, you can run the testnet node with Docker.
-> Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine.
### Generate keychain and get testnet tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null
```
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address.
### Update config file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on Xenon, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Start the miner
-> The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled
```bash
docker run -d \
--name stacks_miner \
--rm \
--network host \
-e RUST_BACKTRACE="full" \
-e STACKS_LOG_DEBUG="1" \
-v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain:latest \
/bin/stacks-node start --config /src/stacks-node/testnet-miner-conf.toml
```
You can review the node logs with this command:
```bash
docker logs -f stacks_miner
```
## Optional: Running in Kubernetes with Helm
In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).
Ensure you have the following prerequisites installed on your machine:
- [Docker](https://docs.docker.com/get-docker/)
- [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster)
- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)
- [helm](https://helm.sh/docs/intro/install/)
### Generate keychain and get some testnet tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null
```
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address.
### Install the chart and run the miner
To install the chart with the release name `my-release` and run the node as a miner:
```bash
minikube start # Only run this if standing up a local Kubernetes cluster
helm repo add blockstack https://charts.blockstack.xyz
helm install my-release blockstack/stacks-blockchain \
--set config.node.miner=true \
--set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step"
```
You can review the node logs with this command:
```bash
kubectl logs -l app.kubernetes.io/name=stacks-blockchain
```
For more information on the Helm chart and configuration options, please refer to the [chart's homepage](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).

211
src/pages/de/understand-stacks/accounts.md

@ -0,0 +1,211 @@
---
title: Accounts
description: Guide to Stacks 2.0 accounts
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Introduction
Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances.
If you want to jump right in to generate and query a new account, try this tutorial:
-> The public-key signature system used for Stacks 2.0 accounts is [Ed25519](https://ed25519.cr.yp.to/).
Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction.
-> The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account
## Creation
An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts.
!> If the seed phrase is lost, access to the associated account cannot be restored. No person or organization, including Blockstack, can recover a lost seed phrase.
The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli):
```bash
# install CLI globally
npm install --global @stacks/cli
# generate a new account and store details in a new file
# '-t' option makes this a testnet account
stx make_keychain -t > cli_keychain.json
```
`make_keychain` creates the following file:
```js
{
"mnemonic": "aaa bbb ccc ddd ...",
"keyInfo": {
"privateKey": "5a3f1f15245bb3fb...",
"address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1",
"btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1",
"wif": "L4HXn7PLmzoNW...",
"index": 0
}
}
```
-> Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details
| Field | Description |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy |
| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` |
| `keyInfo.address` | Stacks address for the account |
| `keyInfo.btcAddress` | Corresponding BTC address for the account. |
| `keyInfo.wif` | Private key of the btcAddress in compressed format. |
| `keyInfo.index` | Nonce for the account, starting at 0 |
Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain.
-> Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method.
Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used:
```js
import {
makeRandomPrivKey,
privateKeyToString,
getAddressFromPrivateKey,
TransactionVersion,
} from '@stacks/transactions';
const privateKey = makeRandomPrivKey();
// Get public key from private
const publicKey = getPublicKey(privateKey);
const stacksAddress = getAddressFromPrivateKey(
privateKeyToString(privateKey),
TransactionVersion.Testnet // remove for Mainnet addresses
);
```
A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`.
#### stacks-gen prerequisite
Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `<command>` exists in \$PATH, or in the local project binaries, and execute that. If `<command>` is not found, it will be installed prior to execution).
```
npm install -g npx
```
#### stacks-gen usage
```
npx -q stacks-gen sk --testnet
{
"phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef",
"private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901",
"public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662",
"stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C",
"stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }",
"btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8",
"wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh"
}
```
-> The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](/understand-stacks/stacking#bitcoin-address).
Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen).
## Querying
### Get Stacks (STX) balance and nonce
STX balance and nonce can be obtained through the [`GET /v2/accounts/<stx_address>`](https://docs.hiro.so/api#operation/get_account_info) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/<stx_address>'
```
Sample response:
```js
{
"balance": "0x0000000000000000002386f26f3f40ec",
"nonce": 17
}
```
-> The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding
### Get all token balances
All token balances can be obtained through the [`GET /extended/v1/address/<stx_address>/balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address/<stx_address>/balances'
```
Sample response:
```js
{
"stx": {
"balance": "0",
"total_sent": "0",
"total_received": "0"
},
"fungible_tokens": {},
"non_fungible_tokens": {}
}
```
-> Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network.
### Get all asset events
All asset events associated with the account can be obtained through the [`GET /extended/v1/address/<stx_address>/assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address/<stx_address>/assets'
```
Sample response:
```js
{
"limit": 20,
"offset": 0,
"total": 0,
"results": [
{
"event_index": 5,
"event_type": "non_fungible_token_asset",
"asset": {
"asset_event_type": "transfer",
"asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft",
"sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR",
"recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G",
"value": {
"hex": "0x0100000000000000000000000000000001",
"repr": "u1"
}
}
},
{
"event_index": 3,
"event_type": "fungible_token_asset",
"asset": {
"asset_event_type": "mint",
"asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19",
"sender": "",
"recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR",
"amount": "12"
}
}
]
}
```

110
src/pages/de/understand-stacks/microblocks.md

@ -0,0 +1,110 @@
---
title: Microblocks
description: Guide to Stacks Microblocks
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Introduction
Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism][], Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks.
Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin.
## Transaction states
The [Stacks block production model][] is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model.
If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known.
Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle:
```
Transaction 1 is broadcast to the mempool. It has 0 confirmations.
Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known
Transaction 1 is included in the next anchor block. It has 1 confirmation.
The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations.
The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations.
...
```
Consider a similar transaction that is not included in a microblock:
```
Transaction 2 is broadcast to the mempool. It has 0 confirmations.
Transaction 2 is included in the next anchor block. It has 1 confirmation.
The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations.
The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations.
```
The lifecycles of the two transactions are similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information.
-> If a transaction is dependent on a chain state that could by altered by previous transactions with serious implications, you should carefully consider whether it should be performed using microblocks.
## Enabling microblocks
Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either.
### Transactions
Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either.
### Mining
Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks][].
## Developing with microblocks
In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative.
A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred.
### Stacks.js libraries
Stacks.js provides the [AnchorMode][] argument on transaction objects so that your application can set the microblocks preference for transactions.
### API
!> API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks.
The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide][] for more details.
## Best practices
Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended.
### Handling nonce
Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal.
### Application design
The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this.
The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application.
#### Explorers
Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state.
#### Wallets
Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state.
#### Exchanges
Continue to count confirmations, microblocks should be considered pending.
#### Applications
Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed.
[Proof-of-Transfer consensus mechanism]: /understand-stacks/proof-of-transfer
[Stacks block production model]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader
[mining microblocks]: /understand-stacks/mining#microblocks
[AnchorMode]: https://stacks-js-git-master-blockstack.vercel.app/enums/transactions.anchormode.html
[Stacks Blockchain API guide]: https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support
[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling
[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks

74
src/pages/de/understand-stacks/mining.md

@ -0,0 +1,74 @@
---
title: Mining
description: A guide to mining on Stacks 2.0
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Introduction
This guide highlights some technical details related to mining on the Stacks 2.0 network.
## Mining frequency
A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee.
## Coinbase rewards
Miners receive coinbase rewards for blocks they win.
The reward amounts are:
- 1000 STX per block are released in the first 4 years of mining
- 500 STX per block are released during the following 4 years
- 250 STX per block are released during the following 4 years
- 125 STX per block are released from then on indefinitely.
These "halvings" are synchronized with Bitcoin halvings.
![coinbase rewards](/images/pages/coinbase-rewards.png)
## Transaction fees
Miners receive Stacks fees for transactions mined in any block they produce.
For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees.
## Reward maturity
Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours.
## Mining with proof-of-transfer
Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain.
![mining with pox](/images/pages/mining-with-pox.png)
100,000 Bitcoin blocks **after** mining begins, the PoX sunset phase begins. During this phase, an increasing proportion of the block commit must be burnt. To burn this sunset fee, the miner must send the sunset fee amount to the first output of their block commit transaction (that is, the OPRETURN output).
400,000 Bitcoin blocks after the sunset phase begins, the sunset phase ends. After this point, PoX is no longer active, and miners must burn all of their leader block commits. They do so by sending Bitcoin to the canonical burn address `1111111111111111111114oLvT2`.
## Probability to mine next block
The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt.
The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent.
While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended.
To calculate the amount of BTC to send miners should:
- Guess the price BTC/STX for the next day (100 blocks later)
- Guess the total amount of BTCs committed by all miners
## Microblocks
The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch.
If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces.
The block streaming model is described in [SIP-001][].
[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader

147
src/pages/de/understand-stacks/network.md

@ -0,0 +1,147 @@
---
title: Network
description: Guide to the Stacks 2.0 network
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Tokens
Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX).
STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6).
## Fees
Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](/understand-stacks/testnet), it is set to 1 micro-STX.
Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer'
```
The API will respond with the fee rate (as integer):
```json
1
```
[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for:
- token transfers (`estimateTransfer`)
- contract deploys (`estimateContractDeploy`)
- non read-only contract calls (`estimateContractFunctionCall`)
-> For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97).
## Nonces
Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction.
Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing.
-> The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers.
When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set.
-> The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling).
## Confirmations
The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain.
The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes.
-> Transactions can also be mined in [microblocks](/understand-stacks/microblocks), reducing the latency significantly.
The block time is hardcoded and will change throughout the implementation phases of the [testnet](/understand-stacks/testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times'
```
The API will respond with the block time (in seconds):
```js
{
"testnet": {
"target_block_time": 120
},
"mainnet": {
"target_block_time": 600
}
}
```
## Read-only function calls
Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted.
However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api).
-> Read-only function calls do not require transaction fees
A read-only contract call can be done using the [`POST /v2/contracts/call-read/<stx_address>/<contract_name>/<function_name>`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read/<stx_address>/<contract_name>/<function_name>' \
--header 'Content-Type: application/json' \
--data-raw '{
"sender": "<stx_address>.<contract_name>",
"arguments": [<clarity_value>, ...]
}'
```
Sample response for a successful call:
```js
{
"okay": true,
"result": "<clarity_value>"
}
```
-> To set the function call arguments and read the result, [Clarity values](/write-smart-contracts/values) need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations
## Querying
Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api).
### Health check
The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain.
### Network info
The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/v2/info'
```
Sample response:
```js
{
"peer_version": 385875968,
"burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37",
"burn_block_height": 1972,
"stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64",
"stable_burn_block_height": 1971,
"server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]",
"network_id": 2147483648,
"parent_network_id": 3669344250,
"stacks_tip_height": 933,
"stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f",
"stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc",
"unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae",
"exit_at_block_height": 28160
}
```

70
src/pages/de/understand-stacks/overview.md

@ -0,0 +1,70 @@
---
title: Overview
description: Learn more about the Stacks 2.0 blockchain
icon: TestnetIcon
images:
large: /images/nodes.svg
sm: /images/nodes.svg
---
## Introduction
Stacks 2.0 is a layer-1 blockchain that connects to Bitcoin and brings smart contracts and decentralized apps to it. Smart contracts and apps developed on the Stacks platform are natively integrated with the security, stability, and economic power of Bitcoin.
## Capabilities
Read more about the features provided by the Stacks 2.0 blockchain.
-> Check out the [technical specifications](/understand-stacks/technical-specs) for a brief overview
A detailed [comparison of the Stacks blockchain to other blockchain technologies][] is available at the Stacks Foundation blog.
### Consensus mechanism
Stacks 2.0 implements a new mining mechanism called Proof of Transfer ("PoX"). PoX is a consensus algorithm between two blockchains. It uses an established blockchain (in this case Bitcoin) to secure a new blockchain (Stacks).
PoX connects to Bitcoin with a 1:1 block ratio, meaning anything that happens on the Stacks blockchain can be verified on the Bitcoin Blockchain.
Instead of burning electricity on proof of work, PoX reuses already minted bitcoins as "proof of computation" and miners represent their cost of mining in bitcoins directly.
[@page-reference | inline] | /understand-stacks/proof-of-transfer
### Mining
Mining is required to make the network usable, trustworthy, and secure. Miners verify incoming transactions, participate in the consensus mechanism, and write new blocks to the blockchain.
To incentivize mining, miners receive freshly minted Stacks (STX) tokens if they win the bid for becoming the leader of the next round.
[@page-reference | inline] | /understand-stacks/mining
### Stacking
Bitcoins used for miner bids are sent to a set of specific addresses corresponding to Stacks (STX) tokens holders that are actively participating in consensus ("Stackers"). Thus, rather than being destroyed, the bitcoins consumed in the mining process go to productive Stacks holders as a reward based on their holdings of Stacks and participation in the Stacking algorithm.
Stackers have to lock up their Stacks (STX) tokens for a certain period of time.
[@page-reference | inline] | /understand-stacks/stacking
### Smart contracts
Clarity is a new language for smart contracts on the Stacks 2.0 blockchain. The Clarity smart contract language optimizes for predictability and security.
Stacks 2.0 anchors clarity smart contracts to Bitcoin making it possible for smart contracts to operate based on actions seen on the bitcoin blockchain.
-> The [Clarity open-source project](https://clarity-lang.org/) is supported by Stacks and [Algorand](https://www.algorand.com/)
Clarity is distinct from other languages designed for writing smart contracts in a few ways:
- **Predictability**: The Clarity language uses precise and unambiguous syntax that allows developers to predict exactly how their contracts will be executed.
- **Security**: The Clarity language allows users to supply their own conditions for transactions that ensure that a contract may never unexpectedly transfer a token owned by a user.
- **No compiler**: Contracts written in Clarity are broadcasted on the Stacks blockchain exactly as they are written by developers. This ensures that the code developers wrote, analyzed, and tested, is exactly what gets executed.
[@page-reference | inline] | /write-smart-contracts/overview
## Guides
Read one of our guides to understand the ins and outs of the Stacks 2.0 blockchain.
[@page-reference | grid-small] | /understand-stacks/accounts, /understand-stacks/transactions, /understand-stacks/network, /understand-stacks/microblocks
[comparison of the Stacks blockchain to other blockchain technologies]: https://stacks.org/stacks-blockchain

57
src/pages/de/understand-stacks/proof-of-transfer.md

@ -0,0 +1,57 @@
---
title: Proof of Transfer
description: Understand the proof-of-transfer consensus mechanism
icon: TestnetIcon
images:
large: /images/stacking.svg
sm: /images/stacking.svg
---
## Overview
Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network.
Popular consensus mechanisms in modern blockchains include proof-of-work, in which nodes dedicate computing resources, and proof-of-stake, in which nodes dedicate financial resources to secure the network.
Proof-of-burn is a novel consensus mechanism where miners compete by ‘burning’ (destroying) a proof-of-work cryptocurrency as a proxy for computing resources.
Proof-of-transfer (PoX) is an extension of the proof-of-burn mechanism. PoX uses the proof-of-work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof-of-burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network.
![PoX mechanism](/images/pox-mechanism.png)
This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, proof-of-transfer blockchains are anchored on their chosen proof-of-work chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain.
![PoX participants](/images/pox-participants.png)
## Why Bitcoin?
There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade.
Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the proof-of-transfer consensus mechanism.
SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md).
![btc-stacks](/images/pox-why-bitcoin.png)
## Blocks and microblocks
The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network.
However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin.
![stx-microblock](/images/stx-microblocks.png)
## Unlocking Bitcoin capital
Stacks also unlocks the hundreds of billions in capital in Bitcoin, and gives Bitcoiners new opportunities to use and earn BTC. Stacks is a accompaniment to the Bitcoin ecosystem, and the two networks working in tandem enables totally novel ways of using BTC. The Stacks ecosystem makes interactive cryptocurrency applications available to Bitcoin holders. Additionally, By stacking STX tokens and participating in the PoX consensus mechanism, users have the opportunity to earn BTC while securing the Stacks chain.
![Unlocking Bitcoin](/images/pox-unlocking-btc.png)
## Clarity and the Bitcoin state
Clarity smart contracts also have unique visibility into the state of the Bitcoin blockchain. This means that contract logic in a Clarity file has the ability to trigger when specific Bitcoin transactions are confirmed. Clarity smart contracts have a built in Simple Payment Verification (SPV) proofs for Bitcoin that make interacting with Bitcoin’s state much simpler for developers. Additionally, Clarity contracts can fork with the original Bitcoin chain. Therefore, in an edge case where Bitcoin forks, developers wouldn’t have to worry about adjusting the deployment of their smart contracts.
## See also
- [Read the full PoX whitepaper](https://community.stacks.org/pox)
- [Watch CEO Muneeb Ali and Evangelist Joe Bender give an overview of Stack's breakthrough PoX mining mechanism](https://www.youtube.com/watch?v=NY_eUrIcWOY)

188
src/pages/de/understand-stacks/running-mainnet-node.md

@ -0,0 +1,188 @@
---
title: Running a mainnet node
description: Set up and run a mainnet node with Docker
icon: MainnetIcon
duration: 15 minutes
experience: beginners
tags:
- tutorial
images:
large: /images/pages/mainnet.svg
sm: /images/pages/mainnet-sm.svg
---
## Introduction
This procedure demonstrates how to run a local mainnet node using Docker images.
-> This procedure focuses on Unix-like operating systems (Linux and MacOS). This procedure has not been tested on Windows.
## Prerequisites
Running a node has no specialized hardware requirements. Users have been successful in running nodes on Raspberry Pi boards and other system-on-chip architectures. In order to complete this procedure, you must have the following software installed on the node host machine:
- [Docker](https://docs.docker.com/get-docker/)
- [curl](https://curl.se/download.html)
- [jq](https://stedolan.github.io/jq/download/)
### Firewall configuration
In order for the API node services to work correctly, you must configure any network firewall rules to allow traffic on the ports discussed in this section. The details of network and firewall configuration are highly specific to your machine and network, so a detailed example isn't provided.
The following ports must open on the host machine:
Ingress:
- stacks-blockchain (open to `0.0.0.0/0`):
- `20443 TCP`
- `20444 TCP`
Egress:
- `8332`
- `8333`
- `20443-20444`
These egress ports are for syncing [`stacks-blockchain`][] and Bitcoin headers. If they're not open, the sync will fail.
## Step 1: initial setup
In order to run the mainnet node, you must download the Docker images and create a directory structure to hold the persistent data from the services. Download and configure the Docker images with the following commands:
```sh
docker pull blockstack/stacks-blockchain
```
Create a directory structure for the service data with the following command:
```sh
mkdir -p ./stacks-node/{persistent-data/stacks-blockchain/mainnet,config/mainnet} && cd stacks-node
```
## Step 2: running Stacks blockchain
First, create the `./config/mainnet/Config.toml` file and add the following content to the file using a text editor:
```toml
[node]
working_dir = "/root/stacks-node/data"
rpc_bind = "0.0.0.0:20443"
p2p_bind = "0.0.0.0:20444"
bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444"
wait_time_for_microblocks = 10000
[burnchain]
chain = "bitcoin"
mode = "mainnet"
peer_host = "bitcoin.blockstack.com"
username = "blockstack"
password = "blockstacksystem"
rpc_port = 8332
peer_port = 8333
[connection_options]
read_only_call_limit_write_length = 0
read_only_call_limit_read_length = 100000
read_only_call_limit_write_count = 0
read_only_call_limit_read_count = 30
read_only_call_limit_runtime = 1000000000
```
Start the [`stacks-blockchain`][] container with the following command:
```sh
docker run -d --rm \
--name stacks-blockchain \
-v $(pwd)/persistent-data/stacks-blockchain/mainnet:/root/stacks-node/data \
-v $(pwd)/config/mainnet:/src/stacks-node \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain \
/bin/stacks-node start --config /src/stacks-node/Config.toml
```
You can verify the running [`stacks-blockchain`][] container with the command:
```sh
docker ps --filter name=stacks-blockchain
```
## Step 3: verifying the services
-> The initial burnchain header sync can take several minutes, until this is done the following commands will not work
To verify the [`stacks-blockchain`][] burnchain header sync progress:
```sh
docker logs stacks-blockchain
```
The output should be similar to the following:
```
INFO [1626290705.886954] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.2% (8000 out of 691034)
INFO [1626290748.103291] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.4% (10000 out of 691034)
INFO [1626290776.956535] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.7% (12000 out of 691034)
```
To verify the [`stacks-blockchain`][] tip height is progressing use the following command:
```sh
curl -sL localhost:20443/v2/info | jq
```
If the instance is running you should recieve terminal output similar to the following:
```json
{
"peer_version": 402653184,
"pox_consensus": "89d752034e73ed10d3b97e6bcf3cff53367b4166",
"burn_block_height": 666143,
"stable_pox_consensus": "707f26d9d0d1b4c62881a093c99f9232bc74e744",
"stable_burn_block_height": 666136,
"server_version": "stacks-node 2.0.11.1.0-rc1 (master:67dccdf, release build, linux [x86_64])",
"network_id": 1,
"parent_network_id": 3652501241,
"stacks_tip_height": 61,
"stacks_tip": "e08b2fe3dce36fd6d015c2a839c8eb0885cbe29119c1e2a581f75bc5814bce6f",
"stacks_tip_consensus_hash": "ad9f4cb6155a5b4f5dcb719d0f6bee043038bc63",
"genesis_chainstate_hash": "74237aa39aa50a83de11a4f53e9d3bb7d43461d1de9873f402e5453ae60bc59b",
"unanchored_tip": "74d172df8f8934b468c5b0af2efdefe938e9848772d69bcaeffcfe1d6c6ef041",
"unanchored_seq": 0,
"exit_at_block_height": null
}
```
## Stopping the mainnet node
Use the following commands to stop the local mainnet node:
```sh
docker stop stacks-blockchain
```
## Optional. Run stacks node with own bitcoin node
It's encouraged to use your own bitcoin node when possible.
To do this simply update the `stacks-node/config/mainnet/Config.toml` file with the details of your bitcoin node. For example:
```
[burnchain]
chain = "bitcoin"
mode = "mainnet"
peer_host = "localhost"
username = "rpc username"
password = "rpc password"
rpc_port = 8332
peer_port = 8333
```
The rpc configuration of your bitcoin node is out of the scope of this document, but you can find more information on how to set it up [here](https://developer.bitcoin.org/examples/intro.html).
## Additional reading
- [Running an API instance with Docker][]
[Running an API instance with Docker]: https://docs.hiro.so/get-started/running-api-node
[`stacks-blockchain`]: https://github.com/stacks-network/stacks-blockchain

141
src/pages/de/understand-stacks/running-testnet-node.md

@ -0,0 +1,141 @@
---
title: Running a testnet node
description: Set up and run a testnet node with Docker
icon: TestnetIcon
duration: 15 minutes
experience: beginners
tags:
- tutorial
images:
large: /images/cli.svg
sm: /images/cli.svg
---
## Introduction
This procedure demonstrates how to run a local testnet node using Docker images.
-> This procedure focuses on Unix-like operating systems (Linux and MacOS). This procedure has not been tested on Windows.
## Prerequisites
Running a node has no specialized hardware requirements. Users have been successful in running nodes on Raspberry Pi boards and other system-on-chip architectures. In order to complete this procedure, you must have the following software installed on the node host machine:
- [Docker](https://docs.docker.com/get-docker/)
- [curl](https://curl.se/download.html)
- [jq](https://stedolan.github.io/jq/download/)
### Firewall configuration
In order for the API node services to work correctly, you must configure any network firewall rules to allow traffic on the ports discussed in this section. The details of network and firewall configuration are highly specific to your machine and network, so a detailed example isn't provided.
The following ports must open on the host machine:
Ingress:
- stacks-blockchain (open to `0.0.0.0/0`):
- `20443 TCP`
- `20444 TCP`
Egress:
- `18332`
- `18333`
- `20443-20444`
These egress ports are for syncing [`stacks-blockchain`][] and Bitcoin headers. If they're not open, the sync will fail.
## Step 1: initial setup
In order to run the testnet node, you must download the Docker images and create a directory structure to hold the persistent data from the services. Download and configure the Docker images with the following commands:
```sh
docker pull blockstack/stacks-blockchain
```
Create a directory structure for the service data with the following command:
```sh
mkdir -p ./stacks-node/persistent-data/stacks-blockchain/testnet && cd stacks-node
```
## Step 2: running Stacks blockchain
Start the [`stacks-blockchain`][] container with the following command:
```sh
docker run -d --rm \
--name stacks-blockchain \
-v $(pwd)/persistent-data/stacks-blockchain/testnet:/root/stacks-node/data \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain \
/bin/stacks-node xenon
```
You can verify the running [`stacks-blockchain`][] container with the command:
```sh
docker ps --filter name=stacks-blockchain
```
## Step 3: verifying the services
-> The initial burnchain header sync can take several minutes, until this is done the following commands will not work
To verify the [`stacks-blockchain`][] burnchain header sync progress:
```sh
docker logs stacks-blockchain
```
The output should be similar to the following:
```
INFO [1626290705.886954] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.2% (8000 out of 2034380)
INFO [1626290748.103291] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.4% (10000 out of 2034380)
INFO [1626290776.956535] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.7% (12000 out of 2034380)
```
To verify the [`stacks-blockchain`][] tip height is progressing use the following command:
```sh
curl -sL localhost:20443/v2/info | jq
```
If the instance is running you should recieve terminal output similar to the following:
```json
{
"peer_version": 4207599105,
"pox_consensus": "12f7fa85e5099755a00b7eaecded1aa27af61748",
"burn_block_height": 2034380,
"stable_pox_consensus": "5cc4e0403ff6a1a4bd17dae9600c7c13d0b10bdf",
"stable_burn_block_height": 2034373,
"server_version": "stacks-node 2.0.11.2.0-rc1 (develop:7b6d3ee+, release build, linux [x86_64])",
"network_id": 2147483648,
"parent_network_id": 118034699,
"stacks_tip_height": 509,
"stacks_tip": "e0ee952e9891709d196080ca638ad07e6146d4c362e6afe4bb46f42d5fe584e8",
"stacks_tip_consensus_hash": "12f7fa85e5099755a00b7eaecded1aa27af61748",
"genesis_chainstate_hash": "74237aa39aa50a83de11a4f53e9d3bb7d43461d1de9873f402e5453ae60bc59b",
"unanchored_tip": "32bc86590f11504f17904ee7f5cb05bcf71a68a35f0bb3bc2d31aca726090842",
"unanchored_seq": 0,
"exit_at_block_height": null
}
```
## Stopping the testnet node
Use the following commands to stop the local testnet node:
```sh
docker stop stacks-blockchain
```
## Additional reading
- [Running an API instance with Docker][]
[Running an API instance with Docker]: https://docs.hiro.so/get-started/running-api-node
[`stacks-blockchain`]: https://github.com/stacks-network/stacks-blockchain

131
src/pages/de/understand-stacks/stacking.md

@ -0,0 +1,131 @@
---
title: Stacking
description: Introduction to the reward mechanism of Proof-of-Transfer
images:
sm: /images/pages/stacking-rounded.svg
---
## Introduction
Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time.
Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks 2.0 network.
-> The Stacking consensus algorithm is implemented as a smart contract, using [Clarity](/write-smart-contracts/overview). [Read more about the contract](#stacking-contract).
## Stacking flow
The Stacking mechanism can be presented as a flow of actions:
![Stacking flow](/images/stacking-illustration.png)
1. Make API calls to get details about the upcoming reward cycle
2. For a specific Stacks account, confirm eligibility
3. Confirm the BTC reward address and the lockup duration
4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase
5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address
6. During the lockup period, details about unlocking timing, rewards and more can be obtained
7. Once the lockup period is passed, the tokens are released and accessible again
8. Display reward history, including details like earnings for previous reward cycles
-> Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network.
If you would like to implement this flow in your own wallet, exchange, or any other application, please have a look at this tutorial:
[@page-reference | inline] | /understand-stacks/integrate-stacking
[@page-reference | inline] | /understand-stacks/stacking-using-CLI
## Stacking delegation flow
The Stacking flow is different for delegation use cases:
![Delegated tacking flow](/images/stacking-delegation-illustration.png)
- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator
- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack
- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking
- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle
- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6)
- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights
## PoX mining
PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol.
-> A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens
![Mining flow](/images/pox-mining-flow.png)
Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases:
- Registration: miners register for a future election by sending consensus data to the network
- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders
- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain
- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens
[@page-reference | inline] | /start-mining/mainnet, /start-mining/testnet
## Token holder eligibility
Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must:
- Commit to participation before a reward cycle begins
- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum
- Lock up STX tokens for a specified period
- Provide a supported Bitcoin address to receive rewards (native segwit is not supported)
The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club.
![Dynamic minimum for individual eligibility](/images/stacking-dynamic-minimum.png)
Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn).
## Stacking in the PoX consensus algorithm
Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm.
![PoX cycles](/images/pox-cycles.png)
- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards
- A reward cycle consists of two phases: prepare and reward
- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle
- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set
- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip
- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned
- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes
## Stacking contract
Check out the [Stacking contract reference](/references/stacking-contract) to see available methods and error codes.
## Bitcoin address
!> You must provide a BTC address in one of two formats: [Legacy (P2PKH)](https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash), which starts with `1`. Or, [Segregated Witness / Segwit (P2SH)](https://en.bitcoin.it/wiki/Pay_to_script_hash), which starts with `3`. The "Native Segwit" format (which starts with "bc1"), for example, is not supported.
The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address.
The address must be specified in the following format using the Clarity language:
```clar
;; a tuple of a version and hashbytes buffer
(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20))))
```
The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following:
```js
SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh
SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh
SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh
SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh
```
The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib):
```js
const btc = require('bitcoinjs-lib');
console.log(
'0x' + btc.address.fromBase58Check('1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6').hash.toString('hex')
);
```

46
src/pages/de/understand-stacks/stacks-blockchain-api.md

@ -0,0 +1,46 @@
---
title: Stacks Blockchain API
description: Interacting with the Stacks 2.0 Blockchain via API
images:
sm: /images/pages/testnet-sm.svg
---
## Introduction
The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain.
~> The RESTful API is developed by Hiro. Hiro also hosts a public API node for easy onboarding. Using it requires you to trust the hosted server, but provides a faster onboarding experience. You can [run your own API server](https://docs.hiro.so/get-started/running-api-node)
The RESTful JSON API can be used without any authorization. The basepath for the API is:
```bash
# for mainnet, replace `testnet` with `mainnet`
https://stacks-node-api.testnet.stacks.co/
```
-> This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api).
### Stacks Node RPC API
The [stacks-node implementation](https://github.com/stacks-network/stacks-blockchain/) exposes JSON RPC endpoints.
All `/v2/` routes a proxied to a Hiro-hosted Stacks Node. For a trustless architecture, you should make these requests to a self-hosted node.
## Proxied Stacks Node RPC API endpoints
The Stacks 2.0 Blockchain API is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node.
-> The Stacks Blockchain API proxies to Node RPC endpoints
While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints:
- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions)
- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface)
- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry)
- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source)
- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info)
- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function)
- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer)
- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info)
~> If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`.

72
src/pages/de/understand-stacks/technical-specs.md

@ -0,0 +1,72 @@
---
title: Technical Specifications
description: Summary of technical specifications of Stacks 2.0
---
## Consensus
- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md)
- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md).
- Threat model
- 51% of malicious Stacks mining power can perform a double-spend attack
- 51% of malicious Bitcoin mining power can reorg the Stacks chain
- Different actors and their roles
- Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream.
- Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle.
- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations.
- For more details, see [Proof of Transfer](/understand-stacks/proof-of-transfer).
## Proof of Transfer Mining
- Coinbase reward schedule:
- 1000 STX/block for first 4 years
- 500 STX/block for following 4 years
- 250 STX/block for subsequent 4 years
- 125 STX/block in perpetuity after that
- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high.
- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks.
- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine.
- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes.
- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust."
- For more details, see [Mining](/understand-stacks/mining).
## Stacking
- Stacking works in 2 phases
1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts
2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks).
- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block.
- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX.
- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation).
- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx).
- Only two types of BTC reward addresses are supported: [Legacy (P2PKH)](https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash) or [Segregated Witness / Segwit (P2SH)](https://en.bitcoin.it/wiki/Pay_to_script_hash). Native Segwit is not supported.
- Further reading: [Stacking](/stacks-blockchain/stacking)
## Accounts and Addresses
- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts
- An account is fully specified by its address + nonce + assets
- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes)
- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above)
- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value.
- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account.
- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use.
- Further reading: [Accounts](/understand-stacks/accounts)
## Transactions
- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock.
- Only standard accounts (not contracts) can pay transaction fees.
- Transaction execution is governed by 3 accounts (may or may not be distinct)
1. _originating account_ is the account that creates, _authorizes_ and sends the transaction
2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction
3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function
- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](/understand-stacks/microblocks)), a faster confirmation time is possible.
- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts.
- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account.
- Mempool limit for concurrent pending transactions is 25 per account
- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours
- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding)
- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying)
- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete.
- Transactions can include a memo string (max 34 bytes)

27
src/pages/de/understand-stacks/testnet.md

@ -0,0 +1,27 @@
---
title: Testnet
description: Test your smart contracts and apps
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## About testnet
The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset.
## Testnet API
The hosted [Stacks Blockchain API](/understand-stacks/stacks-blockchain-api) for the testnet is available at this base URL:
```shell
https://stacks-node-api.testnet.stacks.co/
```
### Faucet
The testnet faucet provides you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. You can get STX from the faucet on the [Stacks Explorer Sandbox](https://explorer.stacks.co/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets).
To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab and click "Request STX" button. If you would like to get enough STX tokens to try out [Stacking](/understand-stacks/stacking), and click "I want to stack."
> The Explorer Sandbox requires you to login with a Secret Key

43
src/pages/de/understand-stacks/transactions.md

@ -0,0 +1,43 @@
---
title: Transactions
description: Guide to Stacks 2.0 transactions
icon: TestnetIcon
images:
large: /images/transaction-signing.svg
sm: /images/transaction-signing.svg
---
## Introduction
Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](/understand-stacks/accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions.
## Lifecycle
Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network.
![Transaction lifecycle](/images/tx-lifecycle.png)
- **Generate**: Transactions are assembled according to the encoding specification.
- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in.
- **Broadcast**: Transactions are sent to a node.
- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions.
- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made.
- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network.
-> A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`.
## Types
The Stacks 2.0 supports a set of different transaction types:
| **Type** | **Value** | **Description** |
| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. |
| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient |
| Contract deploy | `smart_contract` | Contract instantiation |
| Contract call | `contract_call` | Contract call for a public, non read-only function |
| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package |
A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id).
~> Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](/understand-stacks/network#read-only-function-calls).

58
src/pages/de/write-smart-contracts/overview.md

@ -0,0 +1,58 @@
---
title: Clarity overview
description: Overview and guides for getting started with Clarity
images:
large: /images/contract.svg
sm: /images/contract.svg
---
## Introduction
Clarity is a programming language for writing smart contracts on the Stacks 2.0 blockchain. It supports programmatic control over digital assets.
## Smart contracts
Smart contracts encode and enforce rules for modifying a particular set of data that is shared among people and entities who don't necessarily trust each other. For example, a smart contract can hold funds in escrow until multiple parties agree to release them, create its own ledger and keep track of its own novel tokens (fungible or non-fungible), and even help make supply chains more transparent.
Because smart contracts are programs that exist in a blockchain, anyone can query them, and anyone can submit transactions to execute them. A smart contract execution can result in new transactions being written to the blockchain.
Apps can take advantage of smart contracts to manage a global state that is visible to the public. Anyone can audit the blockchain to independently verify that an app's global shared state has been managed correctly according to the smart contract's rules.
There is a [Clarity Visual Studio Code plugin][] available for syntax assistance and debugging.
## Use cases
Not every decentralized application requires smart contracts, but Clarity unlocks interesting capabilities for decentralized applications. Examples of use cases include, but are not limited to:
- Access control (for example pay to access)
- Non-fungible (for example collectibles) and fungible tokens (for example stablecoins)
- Business model templates (for example subscriptions)
- App-specific blockchains
- Decentralized Autonomous Organizations
## Language design
Clarity differs from most other smart contract languages in two essential ways:
- The language is interpreted and broadcast on the blockchain as is (not compiled)
- The language is decidable (not Turing complete)
Using an interpreted language ensures that the executed code is human-readable and auditable. A decidable language like Clarity makes it possible to determine precisely which code is executed, for any function.
A Clarity smart contract consists of two parts, a data space and a set of functions. Only the associated smart contract may modify its corresponding data space on the blockchain. Functions may be private and thus callable only from within the smart contract, or public and thus callable from other contracts. Users call smart contracts' public functions by broadcasting a transaction on the blockchain which invokes the public function. Contracts can also call public functions from other smart contracts.
Note some of the key Clarity language rules and limitations.
- The only primitive types are booleans, integers, buffers, and principals.
- Recursion is illegal and there are no anonymous functions.
- Looping is only performed via `map`, `filter`, or `fold`.
- There is support for lists, however, the only variable length lists in the language appear as function inputs; there is no support for list operations like append or join.
- Variables are immutable.
## Explore more
For language details and references, see the following:
[@page-reference | grid] | /write-smart-contracts/principals, /write-smart-contracts/values, /references/language-overview
[Clarity Visual Studio Code plugin]: https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp

238
src/pages/de/write-smart-contracts/principals.md

@ -0,0 +1,238 @@
---
title: Principals
description: 'Clarity: Understanding Principals'
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Introduction
_Principals_ are a Clarity native type that represents an entity that can have a token balance. This section discusses principals and how they are used in the Clarity.
## Principals and tx-sender
Assets in the smart contracting language and blockchain are "owned" by objects of the principal type, meaning that any object of the principal type may own an asset. For the case of public-key hash and multi-signature Stacks addresses, a given principal can operate on their assets by issuing a signed transaction on the blockchain. _Smart contracts_ may also be principals (represented by the smart contract's identifier), however, there is no private key associated with the smart contract, and it cannot broadcast a signed transaction on the blockchain.
A Clarity contract can use a globally defined `tx-sender` variable to obtain the current principal. The following example defines a transaction type that transfers `amount` microSTX from the sender to a recipient if amount is a multiple of 10, otherwise returning a 400 error code.
```clarity
(define-public (transfer-to-recipient! (recipient principal) (amount uint))
(if (is-eq (mod amount 10) 0)
(stx-transfer? amount tx-sender recipient)
(err u400)))
```
Clarity provides an additional variable to help smart contracts authenticate a transaction sender. The keyword `contract-caller` returns the principal that _called_ the current contract. If an inter-contract call occurred, `contract-caller` returns the last contract in the stack of callers. For example, suppose there are three contracts A, B, and C, each with an `invoke` function such that `A::invoke` calls `B::invoke` and `B::invoke` calls `C::invoke`.
When a user Bob issues a transaction that calls `A::invoke`, the value of `contract-caller` in each successive invoke function's body would change:
```clarity
in A::invoke, contract-caller = Bob
in B::invoke, contract-caller = A
in C::invoke, contract-caller = B
```
This allows contracts to make assertions and perform authorization checks using not only the `tx-sender` (which in this example, would always be "Bob"), but also using the `contract-caller`. This could be used to ensure that a particular function is only ever called directly and never called via an inter-contract call (by asserting that `tx-sender` and `contract-caller` are equal). We provide an example of a two different types of authorization checks in the rocket ship example below.
## Smart contracts as principals
Smart contracts themselves are principals and are represented by the smart contract's identifier -- which is the publishing address of the contract _and_ the contract's name, for example:
```clarity
'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR.contract-name
```
For convenience, smart contracts may write a contract's identifier in the form `.contract-name`. This will be expanded by the Clarity interpreter into a fully qualified contract identifier that corresponds to the same publishing address as the contract it appears in. For example, if the same publisher address, `SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR`, is publishing two contracts, `contract-A` and `contract-B`, the fully qualified identifier for the contracts would be:
```clarity
'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR.contract-A
'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR.contract-B
```
But, in the contract source code, if the developer wishes to call a function from `contract-A` in `contract-B`, they can write
```clarity
(contract-call? .contract-A public-function-foo)
```
This allows the smart contract developer to modularize their applications across multiple smart contracts _without_ knowing the publishing key a priori.
In order for a smart contract to operate on assets it owns, smart contracts may use the special `(as-contract ...)` function. This function executes the expression (passed as an argument) with the `tx-sender` set to the contract's principal, rather than the current sender. The `as-contract` function returns the value of the provided expression.
For example, a smart contract that implements something like a "token faucet" could be implemented as so:
```clarity
(define-map claimed-before
((sender principal))
((claimed bool)))
(define-constant err-already-claimed u1)
(define-constant err-faucet-empty u2)
(define-constant stx-amount u1)
(define-public (claim-from-faucet)
(let ((requester tx-sender)) ;; set a local variable requester = tx-sender
(asserts! (is-none (map-get? claimed-before {sender: requester})) (err err-already-claimed))
(unwrap! (as-contract (stx-transfer? stx-amount tx-sender requester)) (err err-faucet-empty))
(map-set claimed-before {sender: requester} {claimed: true})
(ok stx-amount)))
```
In this example, the public function `claim-from-faucet`:
- Checks if the sender has claimed from the faucet before.
- Assigns the tx sender to a `requester` variable.
- Adds an entry to the tracking map.
- Uses `as-contract` to send 1 microstack
Unlike other principals, there is no private key associated with a smart contract. As it lacks a private key, a Clarity smart contract cannot broadcast a signed transaction on the blockchain.
## Example: Authorization checks
The interactions between `tx-sender`, `contract-caller` and `as-contract` are subtle, but are important when performing authorization checks in a contract. In this example contract, we'll show two different kinds of authorization checks a contract may wish to perform, and then walk through how different ways in which contract functions may be called will pass or fail those checks.
This contract defines a "rocket-ship" non-fungible-token that a principal may own and manage the authorized pilots. Pilots are principals that are allowed to "fly" the rocket ship.
This contract performs two different authorization checks:
1. Before a ship is allowed to fly, the contract checks whether or not the transaction was created and signed by an authorized pilot. A pilot could, for example, call another contract, which then calls the `fly-ship` public function on the pilot's behalf.
2. Before modifying the allowed-pilots for a given rocket ship, the contract checks that the transaction was signed by the owner of the rocket ship. Furthermore, the contract requires that this function be called _directly_ by the ship's owner, rather than through a inter-contract-call.
The second type of check is more restrictive than the first check, and is helpful for guarding very sensitive routines --- it protects users from unknowingly calling a function on a malicious contract that subsequently tries to call sensitive functions on another contract.
```clarity
;;
;; rockets-base.clar
;;
(define-non-fungible-token rocket-ship uint)
;; a map from rocket ships to their allowed
;; pilots
(define-map allowed-pilots
((rocket-ship uint)) ((pilots (list 10 principal))))
;; implementing a contains function via fold
(define-private (contains-check
(y principal)
(to-check { p: principal, result: bool }))
(if (get result to-check)
to-check
{ p: (get p to-check),
result: (is-eq (get p to-check) y) }))
(define-private (contains (x principal) (find-in (list 10 principal)))
(get result (fold contains-check find-in
{ p: x, result: false })))
(define-read-only (is-my-ship (ship uint))
(is-eq (some tx-sender) (nft-get-owner? rocket-ship ship)))
;; this function will print a message
;; (and emit an event) if the tx-sender was
;; an authorized flyer.
;;
;; here we use tx-sender, because we want
;; to allow the user to let other contracts
;; fly the ship on behalf of users
(define-public (fly-ship (ship uint))
(let ((pilots (default-to
(list)
(get pilots (map-get? allowed-pilots { rocket-ship: ship })))))
(if (contains tx-sender pilots)
(begin (print "Flew the rocket-ship!")
(ok true))
(begin (print "Tried to fly without permission!")
(ok false)))))
;;
;; Authorize a new pilot.
;;
;; here we want to ensure that this function
;; was called _directly_ by the user by
;; checking that tx-sender and contract-caller are equal.
;; if any other contract is in the call stack, contract-caller
;; would be updated to a different principal.
;;
(define-public (authorize-pilot (ship uint) (pilot principal))
(begin
;; sender must equal caller: an intermediate contract is
;; not issuing this call.
(asserts! (is-eq tx-sender contract-caller) (err u1))
;; sender must own the rocket ship
(asserts! (is-eq (some tx-sender)
(nft-get-owner? rocket-ship ship)) (err u2))
(let ((prev-pilots (default-to
(list)
(get pilots (map-get? allowed-pilots { rocket-ship: ship })))))
;; don't add a pilot already in the list
(asserts! (not (contains pilot prev-pilots)) (err u3))
;; append to the list, and check that it is less than
;; the allowed maximum
(match (as-max-len? (append prev-pilots pilot) u10)
next-pilots
(ok (map-set allowed-pilots {rocket-ship: ship} {pilots: next-pilots}))
;; too many pilots already
(err u4)))))
```
### Extending functionality: Multi-flyer contract
The authorization scheme for `fly-ship` allows pilots to fly rocket-ships from other contracts. This allows other contracts to provide new functionality built around calling that function.
For example, we can create a contract that calls `fly-ship` for multiple rocket-ships in a single transaction:
```clarity
;;
;; rockets-multi.clar
;;
(define-private (call-fly (ship uint))
(unwrap! (contract-call? .rockets-base fly-ship ship) false))
;; try to fly all the ships, returning a list of whether
;; or not we were able to fly the supplied ships
(define-public (fly-all (ships (list 10 uint)))
(ok (map call-fly ships)))
```
### Authorization for Contract-Owned Assets
The check in `authorize-pilot` protects users from malicious contracts, but how would such a scheme support contract-owned assets? This is what the `as-contract` function is used for. The `as-contract` function executes the supplied closure as if the sender of the transaction was the current contract, rather than the user -- it does this by updating `tx-sender` to the current contract principal. We can use this to, for example, create a smart contract rocket-ship-line:
```clarity
;;
;; rockets-ship-line.clar
;;
(define-constant line-ceo 'SP19Y6GRV9X778VFS1V8WT2H502WFK33XZXADJWZ)
(define-data-var employed-pilots (list 10 principal) (list))
;; This function will:
;; * check that it is called by the line-ceo
;; * check that the rocket is owned by the contract
;; * authorize each employed pilot to the ship
(define-public (add-managed-rocket (ship uint))
(begin
;; only the ceo may call this function
(asserts! (is-eq tx-sender contract-caller line-ceo) (err u1))
;; start executing as the contract
(as-contract (begin
;; make sure the contract owns the ship
(asserts! (contract-call? .rockets-base is-my-ship ship) (err u2))
;; register all of our pilots on the ship
(add-pilots-to ship)))))
;; add all the pilots to a ship using fold --
;; the fold checks the return type of previous calls,
;; skipping subsequent contract-calls if one fails.
(define-private (add-pilot-via-fold (pilot principal) (prior-result (response uint uint)))
(let ((ship (try! prior-result)))
(try! (contract-call? .rockets-base authorize-pilot ship pilot))
(ok ship)))
(define-private (add-pilots-to (ship uint))
(fold add-pilot-via-fold (var-get employed-pilots) (ok ship)))
```
In order for the contract to add each pilot to a new ship, the contract must call `authorize-pilot`. However, the contract wants to perform this action on behalf of a ship the _contract_ owns, not the transaction sender. To do this, the contract uses `as-contract`.

72
src/pages/de/write-smart-contracts/tokens.md

@ -0,0 +1,72 @@
---
title: Tokens
description: Learn about token support within Clarity
icon: TestnetIcon
images:
large: /images/pages/nft/token.png
sm: /images/pages/nft/token.png
---
## Introduction
A fundamental use of blockchain technology is the representation, store, and transfer of value between users of a blockchain. Cryptocurrency is a very common use of blockchain technology, and remains one of the primary drivers of adoption of blockchain technology. Cryptocurrencies are represented by blockchain tokens: individual units of value within a given blockchain ecosystem. Blockchain tokens can extend beyond just digital currency, however, and recent developments throughout the cryptocurrency community have demonstrated potential for the use of blockchain to tokenize and represent not just money but other tangible assets.
A blockchain token is a digital asset that can be verifiably owned by a user of a blockchain. Blockchain tokens are governed by a set of rules that are defined by either the blockchain itself (in the case of native tokens) or by a smart contract on a blockchain. Rules can vary depending on the nature and the use of the token.
Tokens on a blockchain fall into two general categories, depending on their properties: [fungible][] or [non-fungible][]. The following sections discuss the properties of both types of tokens, and provide information about implementation of the two types of tokens on Stacks.
## Fungible tokens
A core property of any token on a blockchain is fungibility. A fungible token is a token that's mutually interchangable or capable of mutual substitution. In other words, one quantity or part of a fungible token can be replaced by an equal quantity or part of the same fungible token. Fungible tokens are often used to represent real-world fungible assets like currency. The STX token is an example of a fungible token. Other examples include stablecoins, tokens that represent voting rights in a DAO, or tokens that algorithmically track the price of stocks.
Fungible tokens form one of the most important value propositions for blockchain technology, the ability to store value and exchange that value through both internal and external transactions. Because fungible tokens can be divided into smaller parts and recombined into the same value representation, they serve a great utility for transferring value between blockchain users.
The primary fungible token on the Stacks blockchain is the native token, STX. Because the Stacks blockchain allows for the creation of [smart contracts][], other fungible tokens can be created on the Stacks blockchain as well. [SIP-010][] specifies the standard for fungible tokens on the Stacks blockchain. This specification defines the functions and traits that a fungible token on Stacks _must_ have. By complying with this standard, fungible tokens on Stacks can be easily represented by wallets that support Stacks.
### Understanding the fungible token standard
The [SIP-010][] standard is an interface definition that allows Stacks applications and wallets to interact with fungible tokens in a standard way. Supporting the standard reduces complexity for token creators to get their tokens into the ecosystem. Under the [SIP-010][] standard, fungible tokens must have the following characteristics:
- Ability to transfer a specified amount of the token to a recipient (`transfer`). The recipient is required to be a Stacks principal.
- Ability to obtain the human-readable name of the token (`get-name`).
- Ability to obtain a short name (ticker symbol) for the token (`get-symbol`).
- Ability to get the number of decimals in the token representation (`get-decimals`). This is used to construct a representation of the token that humans would be familiar dealing with. For example, the US dollar has 2 decimals, if the base unit is cents.
- Ability to get the balance of the token for a particular Stacks principal (`get-balance-of`).
- Ability to get the total supply of the token (`get-total-supply`).
- A URI to metadata associated with the token (`get-token-uri`). This can resolve to off-chain metadata about the token or contract, such as an image icon for the token or a description.
### Examples of fungible tokens on Stacks
- [Nothing](https://nothingtoken.com/) ([contract](https://explorer.stacks.co/txid/0x022bed728d648ff1a68036c40f3aff8136ee22fee18380731df0ab9d76d3c4a9?chain=mainnet))
## Non-fungible tokens (NFTs)
Non-fungible tokens (NFTs) are a type of token that are not interchangeable. NFTs have unique traits (usually in the form of attached metadata) that restrict the abillity to replace them with identical tokens. An NFT is a token that is unique, such as a piece of art, or ownership rights to a real-world asset such as a house.
NFTs alone don't have an inherent value, like a currency. The value of an NFT is derived from the assets that the NFT represents. The use of NFTs are myriad, including digital art, collectibles, domain names, and representation of ownership of content rights. NFTs can be used as digital certificates that track the authenticty of real world items, or digitize the ownership rights to property.
As with fungible tokens, NFTs on the Stacks blockchain are created with [smart contracts][]. [SIP-009][] specifies the standard for NFTs on the Stacks blockchain. This specification defines the functions and traits that an NFT _must_ have, but most NFTs have more functions or traits attached than those solely described by the specification. By complying with this standard, non-fungible tokens on Stacks can be easily represented by wallets that support Stacks.
### Understanding the non-fungible token standard
The [SIP-009][] standard is an interface definition that the Stacks ecosystem aligned on. With support for this standard across wallets and tools, it becomes easy to interact with NFTs. Under the [SIP-009][] standard, NFT contract must have the following characteristics:
- Ability to obtain the last token identifier (`get-last-token-id`). This id represents the upper limit of NFTs issued by the contract.
- A URI to metadata associated with a specific token identifier. (`get-token-uri`). This URI could resolve to a JSON file with information about the creator, associated media files, descriptions, signatures, and more.
- Ability to verify the owner for a given token identifier (`get-owner`). The owner resolves to a [Stacks principal](/write-smart-contracts/principals).
- Ability to transfer an NFT to a recipient (`transfer`). The recipient is required to be a Stacks principal.
### Examples of NFTs on Stacks
- [This is #1](https://thisisnumberone.com) ([contract](https://explorer.stacks.co/txid/SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.thisisnumberone-v2?chain=mainnet))
## Further reading
- [The Difference Between Fungible and Non-Fungible Tokens](https://101blockchains.com/fungible-vs-non-fungible-tokens/)
- [Explain It Like I Am 5: NFTs](https://messari.io/article/explain-it-like-i-am-5-nfts)
[fungible]: #fungible-tokens
[non-fungible]: #non-fungible-tokens-nfts
[smart contracts]: /write-smart-contracts/overview
[SIP-010]: https://github.com/hstove/sips/blob/feat/sip-10-ft/sips/sip-010/sip-010-fungible-token-standard.md
[SIP-009]: https://github.com/friedger/sips/blob/main/sips/sips/sip-009-nft-standard.md

305
src/pages/de/write-smart-contracts/values.md

@ -0,0 +1,305 @@
---
title: Clarity Values
description: Learn how to deal with Clarity Values in JavaScript
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Introduction
The Clarity language makes use of a strong static [type system](/references/language-clarity#clarity-type-system). This simply means that every function defined in Clarity expects arguments of specific types, and that a failure to provide properly typed arguments will result in your code failing to compile, or your contract call transactions failing prior to execution.
In order to build web applications that interact with Clarity contracts, you will need to learn how to construct and use `ClarityValue` objects. The [@stacks/transactions](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library makes this easy, as we will demonstrate below.
## Clarity Types
Please see the following page for information on Clarity Types:
[@page-reference | inline] | /references/language-types
## Constructing Clarity Values and accessing their data
Clarity values can be constructed with functions provided by the [@stacks/transactions](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library. These functions simply output javascript objects that contain a value and a numerical representation of the Clarity type information. The Clarity types are encoded as follows:
```typescript
export enum ClarityType {
Int = 0,
UInt = 1,
Buffer = 2,
BoolTrue = 3,
BoolFalse = 4,
PrincipalStandard = 5,
PrincipalContract = 6,
ResponseOk = 7,
ResponseErr = 8,
OptionalNone = 9,
OptionalSome = 10,
List = 11,
Tuple = 12,
StringASCII = 13,
StringUTF8 = 14,
}
```
`ClarityValue` objects can be serialized and included in transactions that interact with published Clarity contracts.
Here are examples of how to construct each type of Clarity value, and how to access its data if it has any:
### Booleans
```typescript
const t = trueCV();
// { type: ClarityType.BoolTrue }
const f = falseCV();
// { type: ClarityType.BoolFalse }
```
Boolean Clarity Values don't contain any underlying data. They are simply objects with `type` information.
### Optional Values
```typescript
const nothing: NoneCV = noneCV();
// { type: ClarityType.OptionalNone }
const something: SomeCV = someCV(trueCV());
// { type: ClarityType.OptionalSome, value: { type: 4 } }
```
Optional Clarity Values can either be nothing (an empty type that has no data), or something (a wrapped value).
If you are dealing with a function or contract function that returns an `OptionalCV`, you should always check what type it is before trying to access its value.
```typescript
const maybeVal: OptionalCV = await callReadOnlyFunction(...);
if (maybeVal.type === ClarityType.OptionalSome) {
console.log(maybeVal.value);
} else if (maybeVal.type === ClarityType.OptionalNone) {
// deal with `none` value
}
```
### Buffers
```typescript
const buffer = Buffer.from('foo');
const bufCV: BufferCV = bufferCV(buffer);
// { type: ClarityType.Buffer, buffer: <Buffer 66 6f 6f> }
```
### Integers
Clarity supports both integers and unsigned integers.
```typescript
const i: IntCV = intCV(-10);
// { type: ClarityType.Int, value: BN { ... } }
const u: UIntCV = uintCV(10);
// { type: ClarityType.UInt, value: BN { ... } }
```
Clarity value ints store their underlying data as `BigNum` values from the [bn.js](https://github.com/indutny/bn.js/) library.
In order to display/print Clarity (u)int values, use the `cvToString(val)` method.
If you wish to perform arithmetic operations using Clarity (u)int values, you must use methods from the `BigNum` api on their underlying `BigNum` values, and the construct a new Clarity value out of the result. For example:
```typescript
const x = intCV(1);
const y = intCV(2);
x.value.add(y.value);
// 3
```
### Strings
```typescript
const ascii: StringAsciiCV = stringAsciiCV('hello world');
// { type: ClarityType.StringASCII, data: 'hello world' }
const utf8: StringUtf8CV = stringUtf8CV('hello 🌾');
// { type: ClarityType.StringUTF8, data: 'hello 🌾' }
```
Clarity supports both ascii and utf8 strings.
### Principals
```typescript
const address = 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B';
const contractName = 'contract-name';
const spCV = standardPrincipalCV(address);
// {
// type: ClarityType.PrincipalStandard
// address: {
// type: StacksMessageType.Address,
// version: AddressVersion.MainnetSingleSig,
// hash160: "SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B"
// }
// }
const cpCV = contractPrincipalCV(address, contractName);
// {
// type: ClarityType.PrincipalContract,
// contractName: {
// type: StacksMessageType.LengthPrefixedString,
// content: 'contract-name',
// lengthPrefixBytes: 1,
// maxLengthBytes: 128,
// },
// address: {
// type: StacksMessageType.Address,
// version: AddressVersion.MainnetSingleSig,
// hash160: "SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B"
// }
// }
```
Both kinds of Clarity principal values contain `type` information and an `address` object. Contract principals also contain a `contractName`.
### Response Values
```typescript
const errCV = responseErrorCV(trueCV());
// { type: ResponseErr, value: { type: ClarityType.BoolTrue } }
const okCV = responseOkCV(falseCV());
// { type: ResponseOk, value: { type: ClarityType.BoolFalse } }
```
Response Clarity Values will either have the type `ClarityType.ResponseOk` or `ClarityType.ResponseErr`. They both contain a Clarity Value. Often this value will be an integer error code if the response is an `Error`.
### Tuples
```typescript
const tupCV = tupleCV({
a: intCV(1),
b: trueCV(),
c: falseCV(),
});
// {
// type: ClarityType.Tuple,
// data: {
// a: { type: ClarityType.Int, value: BN { ... } },
// b: { type: ClarityType.BoolTrue },
// c: { type: ClarityType.BoolFalse },
// }
// }
console.log(tupCV.data['b']);
// { type: ClarityType.BoolTrue }
```
Tuples in Clarity are typed and contain named fields. The tuple above, for example, contains three fields with the names **a**, **b** and **c**, and the types of their values are `Int`, `Boolean` and `Boolean`, respectively.
Clarity tuples are represented in JavaScript as objects and a tuple's data can be accessed by its `data` field, where the underlying JS object is stored.
### Lists
```typescript
const l = listCV([trueCV(), falseCV()]);
// { type: ClarityType.List, list: [{ type: ClarityType.BoolTrue }] }
console.log(l.list[0]);
// { type: ClarityType.BoolTrue }
```
Lists, in Clarity, are homogeneous, meaning they can only contain elements of a singular (Clarity) type. Make sure to avoid constructing lists that have elements of multiple types.
A Clarity lists underlying data can be accessed via its `list` field.
## Using Clarity Values
Now that you know how to construct _and_ deconstruct Clarity values, you can use them to build `contract-call` transactions that call smart contract functions, and you can utilize their responses.
This is covered in depth [here](/understand-stacks/transactions#construction).
## Utilizing Clarity Values from Transaction Responses
`Read-only` Clarity functions can return Clarity values as a response. These `read-only` functions can be accessed easily in JavaScript via the [`callReadOnlyFunction()`](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#calling-read-only-contract-function) function included in `@stacks/transactions`, which returns a `ClarityValue`.
As mentioned above, `ClarityValues` are simply javascript objects containing a value and its associated Clarity type information. These object types are defined [here](https://github.com/hirosystems/stacks.js/tree/1f2b5fd8bdf1c2b5866e8171163594d7708a8c7a/packages/transactions/src/clarity/types).
When you are calling a `read-only` contract function, you will always know what type the function will return, since functions in Clarity are strongly typed.
It is common for Clarity functions to return values wrapped in a `Response`, in order to indicate if there was success or an error.
Since every `ClarityValue` has a `type` field, the type of the result of a `read-only` function call can be checked and acted upon like so:
```typescript
const contractAddress = 'ST3KC0MTNW34S1ZXD36JYKFD3JJMWA01M55DSJ4JE';
const contractName = 'kv-store';
const functionName = 'get-value';
const buffer = bufferCVFromString('foo');
const network = new StacksTestnet(); // for mainnet, use `StacksMainnet()`
const senderAddress = 'ST2F4BK4GZH6YFBNHYDDGN4T1RKBA7DA1BJZPJEJJ';
const options = {
contractAddress,
contractName,
functionName,
functionArgs: [buffer],
network,
senderAddress,
};
// make a read-only call to a contract function that
// returns a Response
const result: ResponseCV = await callReadOnlyFunction(options);
if (result.type === ClarityType.ResponseOk) {
console.log(cvToString(result.value));
} else if (result.type === ClarityType.ResponseErr) {
throw new Error(`kv-store contract error: ${result.value.data}`);
}
```
### ClarityValues to/from Hex
If you receive a response from a transaction in the form of a `hex` string, you can deserialize it into a Clarity value like so:
```javascript
import { hexToCV } from '@stacks/transactions';
let cv = hexToCV('hex_string');
```
Similarly, you can convert a Clarity value to `hex` string like so:
```javascript
import { cvToHex, trueCV } from '@stacks/transactions';
let trueHex = cvToHex(trueCV());
```
## Debugging Clarity Values
Sometimes you might receive a Clarity value that you were not expecting. Logging the value to your console won't always prove to be useful, unless you have memorized the Clarity value type enum values.
In order to figure out what kind of value you are dealing with, you can use the `cvToString()` function to convert the Clarity value to a more easily readable string.
For example, calling `cvToString()` on a large `tuple` might yield something like:
```
(tuple
(a -1)
(b u1)
(c 0x74657374)
(d true)
(e (some true))
(f none)
(g SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B)
(h SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B.test)
(i (ok true))
(j (err false))
(k (list true false))
(l (tuple (a true) (b false)))
(m "hello world")
(n u"hello \u{1234}"))`
```

24
src/pages/es/404.md

@ -0,0 +1,24 @@
---
title: Página no encontrada
description: La página que busca no se encuentra aquí.
---
## ¡Vaya!
Looks like the page you are looking for isn't here.
-> Developer content has recently moved to [docs.hiro.so](https://docs.hiro.so/). For more information on the content move, see [this post](https://forum.stacks.org/t/the-evolution-of-the-stacks-documentation-and-a-new-hiro-docs-site/12343) on the Stacks forum. Check for your content at [docs.hiro.so](https://docs.hiro.so/) or ask in Discord if you believe you have reached this page in error.
Try out some of these popular pages:
## Understand Stacks
[@page-reference | grid] | /understand-stacks/overview, /understand-stacks/proof-of-transfer, /understand-stacks/testnet
## Write smart contracts
[@page-reference | grid] | /write-smart-contracts/overview
## Start mining
[@page-reference | grid] | /start-mining/mainnet, /start-mining/testnet

27
src/pages/es/build-apps/overview.md

@ -0,0 +1,27 @@
---
title: Build apps with Stacks
description: Authenticate users, sign transactions and store data with the Stacks blockchain
images:
large: /images/pages/build-apps.svg
sm: /images/pages/build-apps-sm.svg
---
## Introduction
Apps built with the Stacks blockchain give users control over their digital identities, assets, and data.
Unlike most cloud-based apps, they are "decentralized" since they don't depend on any centralized platform, server, or database to function. Rather, they use the Stacks blockchain to authenticate users and facilitate read and write requests for them without any single point of failure or trust.
Stacks provides three main functions for building apps:
- **Authentication**: Register and sign users in with identities on the Stacks blockchain
- **Transaction signing**: Prompt users to sign and broadcast transactions to the Stacks blockchain
- **Data storage**: Save and retrieve data for users with [Gaia](/build-apps/references/gaia)
All three of these integrations can be used together to create powerful new user experiences that rival or exceed those of traditional apps—all while protecting your users' digital rights.
While integration is possible for any type of app, most of the resources available here are for web developers experienced with JavaScript. See [Hiro developer docs](https://docs.hiro.so) for more information on the available app development libraries for Stacks.
## References
[@page-reference | grid] | /build-apps/references/authentication, /build-apps/references/bns, /build-apps/references/gaia

65
src/pages/es/build-apps/references/authentication.md

@ -0,0 +1,65 @@
---
title: Authentication
description: Register and sign in users with identities on the Stacks blockchain
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Introduction
This guide explains how authentication is performed on the Stacks blockchain.
Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite.
Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](/build-apps/references/bns) and vice versa.
## How it works
The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side.
An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token.
These tokens are are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings.
When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter:
`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...`
When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`.
The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`.
The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions:
1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub
2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage.
3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions.
Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain.
The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/build-apps/references/gaia).
## Key pairs
Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular.
The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed.
### Transit private key
The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response.
The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request.
### Identity address private key
The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator.
This private key signs the authentication response token for an app to indicate that the user approves sign in to that app.
### App private key
The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input.
The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key.

244
src/pages/es/build-apps/references/bns.md

@ -0,0 +1,244 @@
---
title: Blockchain Naming System
description: Binds Stacks usernames to off-chain state
images:
large: /images/nodes.svg
sm: /images/nodes.svg
---
Blockchain Naming System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control.
The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block.
Names in BNS have three properties:
- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state.
- **Names are human-meaningful.** Each name is chosen by its creator.
- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys.
The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network.
The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions.
## Motivation behind naming systems
We rely on naming systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's naming system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key.
What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be.
- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to.
- **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes.
- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states.
- **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene.
- In PGP, names are key IDs. They are are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference.
- **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system.
BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more:
- Build domain name services where hostnames can't be hijacked.
- Build social media platforms where user names can't be stolen by phishers.
- Build version control systems where repository branches do not conflict.
- Build public-key infrastructure where it's easy for users to discover and remember each other's keys.
## Organization of BNS
BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming:
- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators.
- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already.
- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules.
A feature comparison matrix summarizing the similarities and differences between these name objects is presented below:
| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** |
| -------------------------------------- | -------------- | ------------- | ------------------ |
| Globally unique | X | X | X |
| Human-meaningful | X | X | X |
| Owned by a private key | | X | X |
| Anyone can create | X | X | [1] |
| Owner can update | | X | [1] |
| State hosted on-chain | X | X | |
| State hosted off-chain | | X | X |
| Behavior controlled by consensus rules | X | X | |
| May have an expiration date | | X | |
[1] Requires the cooperation of a BNS name owner to broadcast its transactions
## Namespaces
Namespaces are the top-level naming objects in BNS.
They control a few properties about the names within them:
- How expensive they are to register
- How long they last before they have to be renewed
- Who (if anyone) receives the name registration fees
- Who is allowed to seed the namespace with its initial names.
At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered unspendable (the intention is to discourage ID squatters).
Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever.
However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`).
Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`.
## Subdomains
BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth.
BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations.
This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored.
For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file:
```bash
$TTL 3600
1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg=="
2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK"
10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo="
31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg=="
359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo="
30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg=="
onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg=="
10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo="
36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg=="
_http._tcp URI 10 1 "https://dotpodcast.co/"
```
Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to:
```json
{
"address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH",
"blockchain": "bitcoin",
"last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339",
"status": "registered_subdomain",
"zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3",
"zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n"
}
```
This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`.
### Subdomain Lifecycle
Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`.
The lifecycle of a subdomain and its operations is shown in Figure 2.
```
subdomain subdomain subdomain
creation update transfer
+----------------+ +----------------+ +----------------+
| cicero | | cicero | | cicero |
| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." |
| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ...
| seqn=0 | | seqn=1 | | seqn=2 |
| | | sig="xxxx" | | sig="xxxx" |
+----------------+ +----------------+ +----------------+
| | |
| off-chain | |
~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ...
| on-chain | |
V V (zone file hash ) V
+----------------+ +----------------+ +----------------+
| res_publica.id | | jude.id | | res_publica.id |
| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ...
+----------------+ +----------------+ +----------------+
blockchain blockchain blockchain
block block block
Figure 2: Subdomain lifetime with respect to on-chain name operations .A new
subdomain operation will only be accepted if it has a later "sequence=" number,
and a valid signature in "sig=" over the transaction body .The "sig=" field
includes both the public key and signature, and the public key must hash to
the previous subdomain operation's "addr=" field.
The subdomain-creation and subdomain-transfer transactions for
"cicero.res_publica.id" are broadcast by the owner of "res_publica.id."
However, any on-chain name ("jude.id" in this case) can broadcast a subdomain
update for "cicero.res_publica.id."
```
Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include:
- The next sequence number
- The public key that hashes to the previous subdomain transaction's address
- A signature from the corresponding private key over the entire subdomain operation.
If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored.
Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain.
### Subdomain Creation and Management
Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular:
- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`.
- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key.
- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files.
- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`.
That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner.
Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network.
If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it.
### Subdomain Registrars
Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin.
We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application.
# BNS and DID Standards
BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs).
Each name in BNS has an associated DID. The DID format for BNS is:
```bash
did:stack:v0:{address}-{index}
```
Where:
- `{address}` is an on-chain public key hash (for example a Bitcoin address).
- `{index}` refers to the `nth` name this address created.
For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`.
As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`).
The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not.
Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name:
- The name must exist
- The name's zone file hash must be the hash of a well-formed DNS zone file
- The DNS zone file must be present in the Stacks node's data.
- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token
- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name
Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do.
A RESTful API is under development.
## DID Encoding for Subdomains
Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take.
- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses).
- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively.
The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63).

92
src/pages/es/build-apps/references/gaia.md

@ -0,0 +1,92 @@
---
title: Gaia
description: Decentralized storage architecture for off-chain data
images:
large: /images/pages/data-storage.svg
sm: /images/pages/data-storage-sm.svg
---
## Introduction
Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia.
Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage.
Storing data off of the blockchain ensures that Stacks applications can provide users with high performance and high availability for data reads and writes without introducing central trust parties.
## Understand Gaia in the Stacks architecture
The following diagram depicts the Stacks architecture and Gaia's place in it:
![Stacks Architecture](/images/architecture.png)
Blockchains require consensus among large numbers of people, so they can be slow. Additionally, a blockchain is not designed to hold a lot of data. This means using a blockchain for every bit of data a user might write and store is expensive. For example, imagine if an application were storing every tweet in the chain.
The Stacks blockchain addresses performance problems using a layered approach. The base layer consists of the Stacks blockchain and the Blockchain Naming System (BNS). The blockchain governs ownership of identities in the Stacks network. Identities can be names such as domain names, usernames, or application names.
When an identity is created, its creation is recorded in the Stacks blockchain. Identities make up the primary data stored into the Stacks blockchain. These identities correspond to routing data in the OSI stack. The routing data is stored in the Atlas Peer Network, the second layer. Every core node that joins the Stacks Network is able to obtain an entire copy of this routing data. Stacks uses the routing data to associate identities (domain names, user names, and application names) with a particular storage location in the final layer, the Gaia Storage System.
A Gaia Storage System consists of a _hub service_ and storage resource on a cloud software provider. The storage provider can be any commercial provider such as Azure, DigitalOcean, Amazon EC2, and so forth. Typically the compute resource and the storage resource reside same cloud vendor, though this is not a requirement. Gaia currently has driver support for S3, Azure Blob Storage, Google Cloud Platform and local disk, but the driver model allows for other backend support as well.
Gaia stores data as a simple key-value store. When an identity is created, a corresponding data store is associated with that identity on Gaia. When a user logs into a dApp, the authentication process gives the application the URL of a Gaia hub, which then writes to storage on behalf of that user.
The Stacks blockchain stores only identity data. Data created by the actions of an identity is stored in a Gaia Storage System. Each user has profile data. When a user interacts with a decentralized dApp that application stores application data on behalf of the user. Because Gaia stores user and application data off the blockchain, a Stacks DApp is typically more performant than DApps created on other blockchains.
## User control or how is Gaia decentralized?
A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider.
![Gaiastorage](/images/gaia-storage.png)
Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data.
The control of user data lies in the way that user data is accessed. When an application fetches a file `data.txt` for a given user `alice.id`, the lookup will follow these steps:
1. Fetch the `zonefile` for `alice.id`.
2. Read her profile URL from her `zonefile`.
3. Fetch Alice's profile.
4. _Verify_ that the profile is signed by `alice.id`'s key
5. Find the read-only url out of the profile's `appsMeta` section (e.g. `https://example-app.gaia.alice.org`).
6. Fetch the file from `https://example-app.gaia.alice.org/data.txt`.
Because `alice.id` has access to her [zonefile](https://docs.stacks.co/references/bns-contract#name-update), she can change where her profile is stored. For example, she may do this if the current profile's service provider or storage is compromised. To change where her profile is stored, she changes her Gaia hub URL to another Gaia hub URL. If a user has sufficient compute and storage resources, a user may run their own Gaia Storage System and bypass a commercial Gaia hub provider all together.
~> Users with existing identities cannot yet migrate their data from one hub to another.
Applications writing directly on behalf of `alice.id` do not need to perform a lookup. Instead, the [Stacks authentication flow](http://blockstack.github.io/stacks.js/index.html) provides Alice's chosen gaia hub URL to the application. This authentication flow _is also_ within Alice's control because Alice's wallet _must_ generate the authentication response.
## Understand data storage
A Gaia hub stores the written data _exactly_ as given. It offers minimal guarantees about the data. It does not ensure that data is validly formatted, contains valid signatures, or is encrypted. Rather, the design philosophy is that these concerns are client-side concerns.
Client libraries (such as [`Stacks.js`](https://stacks.js.org/)) are capable of providing these guarantees. A liberal definition of the [end-to-end principle](https://en.wikipedia.org/wiki/End-to-end_principle) guides this design decision.
When an application writes to a Gaia hub, an authentication token, key, and the data are passed to the Gaia hub.
![Gaia writes](/images/gaia-writes.png)
The token ensures the app has the authorization to write to the hub on the user's behalf.
## Gaia versus other storage systems
Here's how Gaia stacks up against other decentralized storage systems. Features that are common to all storage systems are omitted for brevity.
| Features | [Gaia](https://github.com/stacks-network/gaia) | [Sia](https://sia.tech/) | [Storj](https://storj.io/) | [IPFS](https://ipfs.io/) | [DAT](https://datproject.org/) | [SSB](https://www.scuttlebutt.nz/) |
| ------------------------------------------ | ---------------------------------------------- | ------------------------ | -------------------------- | ------------------------ | ------------------------------ | ---------------------------------- |
| User controls where data is hosted | X | | | | | |
| Data can be viewed in a normal Web browser | X | | | X | | |
| Data is read/write | X | | | | X | X |
| Data can be deleted | X | | | | X | X |
| Data can be listed | X | X | X | | X | X |
| Deleted data space is reclaimed | X | X | X | X | | |
| Data lookups have predictable performance | X | | X | | | |
| Writes permission can be delegated | X | | | | | |
| Listing permission can be delegated | X | | | | | |
| Supports multiple backends natively | X | | X | | | |
| Data is globally addressable | X | X | X | X | X | |
| Needs a cryptocurrency to work | | X | X | | | |
| Data is content-addressed | | X | X | X | X | X |
## Deploy your GAIA hub
Steps to deploy your own GAIA hub can be found [here](https://github.com/stacks-network/gaia/blob/master/deploy/README.md)

268
src/pages/es/contributing.md

@ -0,0 +1,268 @@
---
title: How to contribute
description: Learn how this site is built, and how you could contribute to it.
icon: BlockstackIcon
images:
large: /images/contribute.svg
sm: /images/contribute.svg
---
## Introduction
Welcome. Thank you for your interest in contributing and helping make these docs as good as they can be. This page will outline how this site is built, its general structure, getting it running locally, and some helpful tips for using all of its features.
## Next.js, MDX, Markdown
This docs site is built with [Next.js](https://github.com/vercel/next.js) and uses something called [MDX](https://mdxjs.com/). Next.js is a framework built on top of React, and MDX is a tool that enables writing React code (JSX) within standard Markdown files. In addition to being able to write JSX in Markdown, it allows the application to render out all of the Markdown content with React components. This means that we are able to do some pretty complex things while a contributor only has to know how to write Markdown.
-> **Don't know what Markdown is?** Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/) for learning it.
## Getting started
To get started you have two options:
1. using web IDE Gitpod in your browser.
2. working locally.
### Working in browser
The web IDE gitpod provides an environment to contibute directly from within your browser.
To get started, you only have to a github account and open the link [https://gitpod.io/#https://github.com/stacks-network/docs](https://gitpod.io/#https://github.com/stacks-network/docs) in your browser.
### Working Locally
When workin locally with the site, a few things are needed:
- Familiarity with `git`, GitHub, and the command line. [Read more here.](https://docs.github.com/en/github/getting-started-with-github/quickstart)
- [`node` + `npm`,](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) and [`yarn` installed](https://yarnpkg.com/getting-started/install) on your machine.
- Some kind of code editor, such as VSCode, Sublime, or WebStorm.
-> This project requires at least Node version 12
### Working with GitHub
All of the code for this site is open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). Before you start editing anything, you will need to fork the repo so that you can have your own copy of the code under your GitHub profile. On the [repository's page](https://github.com/stacks-network/docs), you should be able to see a button in the upper right of the screen that says "Fork." [You can read about Forking here.](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo)
This is a generalized workflow for contributing to these docs:
- Clone your fork to your local machine with this command `git clone git@github.com:<YOUR_USERNAME>/docs.git stacks_docs`
- Enter your project folder `cd stacks_docs`
- Create a branch `git checkout -b feat/my-feature-branch`.
- Run the command `yarn` to install all of the dependencies.
- Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`.
- Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`.
- Visit GitHub and make your pull request.
### Running the site locally
Once you have the project on your computer and the dependencies have been installed via the `yarn` command, you can run `yarn dev` and it should give you a message such as:
```bash
yarn dev
```
```bash
yarn run v1.22.17
$ yarn clean:build-files && next dev
$ rimraf .next && rimraf .cache
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
warn - You have enabled experimental feature(s).
warn - Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use them at your own risk.
info - Disabled SWC as replacement for Babel because of custom Babel configuration "babel.config.js" https://nextjs.org/docs/messages/swc-disabled
info - automatically enabled Fast Refresh for 1 custom loader
info - Using external babel configuration from /home/alejandro/stacks-network_docs/babel.config.js
event - compiled client and server successfully in 13.5s (680 modules)
```
The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000).
## Project structure
### Pages
If you are interested in only adding new documentation content to the site, the files that will be important to you are located within `./src/pages/*`:
```bash showLineNumbers highlight=11
stacks_docs/
.github/
lib/
node_modules/
public/
src/
_data/
_includes/
common/
components/
pages/
types/
```
The routing for this site is file based, meaning if you created a folder within `/pages` named `clarity` and a then file named `overview.md`, you would be able to navigate to `http://localhost:3000/clarity/overview` and you would see whatever content is in that markdown file.
### Frontmatter
Frontmatter is the top part of any markdown document that is written in a language called [YAML](https://yaml.org/). It looks like this:
```yaml
---
title: This is my page title
description: A short, concise sentence describing what is on this page
---
```
Frontmatter gives us the ability to define some things within a page that the site can use, such as a page title or page description. When adding any new page, please include a `title` and `description`.
-> **Did you know?** The term _Frontmatter_ comes from the section in a book at the beginning detailing things like: publisher’s name and address, copyright information, table of contents, etc.
### Dynamic sidebar
The sidebar navigation is generated in a partially dynamic way. The application searches through a list of paths and parses the markdown to get some information about the page, such as the title and headings contained within the page.
#### Adding a new route
If you are adding a new route, you have to add your route to a section contained within this file: `src/common/navigation.yaml`
```bash showLineNumbers highlight=11
sections:
- pages:
- path: /
- path: /understand-stacks
pages:
- path: /overview
- path: /testnet
- path: /proof-of-transfer
- path: /mining
- path: /accounts
- path: /transactions
- path: /network
- path: /stacking
- path: /command-line-interface
- path: /local-development
- path: /technical-specs
- path: /stacks-blockchain-api
sections:
- title: Tutorials
pages:
- path: /managing-accounts
- path: /sending-tokens
- path: /running-testnet-node
- path: /integrate-stacking
- path: /stacking-using-CLI
```
Adding a new route requires to add a new `path`.
The script will process that file and pull out the title from the frontmatter of the document.
### Non-standard pages
There are a few pages within these docs that are non-standard markdown pages. This means they are using some kind of external data as their source, such as the [Clarity Reference page](/references/language-overview), or the [Stacks CLI page](https://docs.hiro.so/references/stacks-cli). These pages are using a function of Next.js called [`getStaticProps`](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) which allows us to fetch external data at runtime and use it in some way within our pages.
## Tips and tricks
### Style checks
We use the [Google Developer documentation style guides](https://developers.google.com/style/) in this project. Make sure to install [vale](https://github.com/errata-ai/vale) and run the style checks before you create a PR:
```bash
yarn check:style
```
### Use Conventional Commits
We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please.
### Always use Markdown when possible
It's possible to write standard HTML when writing in Markdown, but that should be avoided at all costs. We use `remark` to processes all Markdown, giving us things like automatically opening all external links in new windows, and adding IDs to headers. When we write things in HTML, such as a link or image, we don't get the benefit of the remark plugins as consistently as we would if we stuck to standar Markdown.
### Code blocks
The site uses `react-prism-renderer` and `prismjs` to add syntax highlighting to all of our code. You can see a full list of [languages supported here](https://github.com/PrismJS/prism/tree/master/components). We have a custom language definition for `clarity`, our smart contracting language located here. To add a new language, see this file: [`components/codeblock/index.tsx`](#).
To write a code block, you need to wrap your code in ` ```language `, and end your code block with ` ``` `. Here is an example of ` ```clarity `.
```clarity
(define-data-var counter int 0)
(define-public (get-counter)
(ok (var-get counter)))
```
#### Line highlighting
You can pass some extra data to tell the component to highlight specific lines:
` ```clarity highlight=1,4-6,13-17,28-32 `
Which will render:
```clarity highlight=1,4-6,13-17,28-32
(define-constant sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)
(define-constant recipient 'SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G)
(define-fungible-token novel-token-19)
(begin (ft-mint? novel-token-19 u12 sender))
(begin (ft-transfer? novel-token-19 u2 sender recipient))
(define-non-fungible-token hello-nft uint)
(begin (nft-mint? hello-nft u1 sender))
(begin (nft-mint? hello-nft u2 sender))
(begin (nft-transfer? hello-nft u1 sender recipient))
(define-public (test-emit-event)
(begin
(print "Event. Hello world")
(ok u1)))
(begin (test-emit-event))
(define-public (test-event-types)
(begin
(unwrap-panic (ft-mint? novel-token-19 u3 recipient))
(unwrap-panic (nft-mint? hello-nft u2 recipient))
(unwrap-panic (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR))
(unwrap-panic (stx-burn? u20 tx-sender))
(ok u1)))
(define-map store ((key (buff 32))) ((value (buff 32))))
(define-public (get-value (key (buff 32)))
(begin
(match (map-get? store ((key key)))
entry (ok (get value entry))
(err 0))))
(define-public (set-value (key (buff 32)) (value (buff 32)))
(begin
(map-set store ((key key)) ((value value)))
(ok u1)))
```
### Alerts
We use another remark plugin to generate certain kinds of alerts inline in our documentation.
```md
> This is a standard blockquote (non-alert).
-> This will be a standard note style alert.
=> This will be a success style alert.
~> This will be a warning style alert
!> This will be a danger style alert
```
Which renders:
> This is a standard blockquote (non-alert).
-> This will be a standard note style alert.
=> This will be a success style alert.
~> This will be a warning style alert
!> This will be a danger style alert

18
src/pages/es/index.md

@ -0,0 +1,18 @@
---
title: Documentación Stacks
description: Aprende sobre el minado de Stacks, el token STX y el lenguaje de programación de contratos inteligentes, Clarity
---
-> Content related to developer tools and app development has recently moved to [docs.hiro.so](https://docs.hiro.so/). For more information on the content move, see [this post](https://forum.stacks.org/t/the-evolution-of-the-stacks-documentation-and-a-new-hiro-docs-site/12343) on the Stacks forum.
## Understand Stacks
[@page-reference | grid] | /understand-stacks/overview, /understand-stacks/proof-of-transfer, /understand-stacks/testnet
## Write smart contracts
[@page-reference | grid] | /write-smart-contracts/overview, /write-smart-contracts/tokens
## Start mining
[@page-reference | grid] | /start-mining/mainnet, /start-mining/testnet

24
src/pages/es/references/bns-contract.md

@ -0,0 +1,24 @@
---
title: BNS Contract
description: See a detailed list of all functions and error codes of the BNS contract.
---
export { convertBNSRefToMdx as getStaticProps } from '@common/data/bns-ref'; import { BNSErrorcodeReference, BNSFunctionReference } from '@components/bns-ref';
## Introduction
The [Blockchain Naming System (BNS)](/build-apps/references/bns) is implemented as a smart contract using Clarity.
Below is a list of public and read-only functions as well as error codes that can be returned by those methods.
## Public functions
<BNSFunctionReference {...props.mdx.publicFunctions} />
## Read-only functions
<BNSFunctionReference {...props.mdx.readonlyFunctions} />
## Error codes
<BNSErrorcodeReference {...props.mdx.errorCodes} />

51
src/pages/es/references/deploy-tips.md

@ -0,0 +1,51 @@
---
title: Deploy tips
description: Learn some common methods for deploying your application.
---
## Introduction
Stacks applications are web applications that authenticate users with Stacks Auth and store data with Gaia. Both of these technologies can be accessed on the client side. As such, Stacks apps tend to be simple in design and operation, since in many cases, they don’t have to host anything besides the application’s assets.
## Where to deploy your application
Before users can interact with your application, you must deploy it on a server that is accessible over the internet. Deploying requires that you:
- Configure or customize the files in the `public` directory.
- Build your application site for deployment.
- Copy your generated application files to your production server.
If you first populated your application with the Stacks application generator, your application contains the starting blocks for configuring, building, and deploying your app. For example, the React template builds out a scaffolding with the following building blocks.
| File or Directory | Description |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| node_modules/react-scripts | A set of scripts for that helps you kick off React projects without configuring, so you do not have to set up your project by yourself. |
| package.json | Contains a scripts section that includes a reference to the react-scripts, which are a dependency. This script creates a build directory containing your files for deployment. |
| public/favicon.ico | An example shortcut icon. |
| public/index.html | An entry page for an application. |
| public/manifest.json | A JSON file that describes your web application to the browser. |
| cors | Contains example deployment files for cross-origin request configuration. |
If you use the generator to build JavasScript or Vue scaffolding, your project configuration files will be different.
Regardless of which scaffolding you use, you must customize and extend this basic scaffolding as needed by your application. For example, you may want to add more properties to the `manifest.json` file. Since every application is different, Stacks Auth cannot give you specific instructions on how to do this. The steps you take are specific to your application.
## Stacks Authentication and deployment
When your application authenticates users with Stacks, the Stacks Wallet at on URL requests a resource (the app manifest) from your DApp. A request for a resource outside of the origin (the Stacks Wallet) is called as a _cross-origin request_(CORs). Getting data in this manner can be risky, so you must configure your website security to allow interactions across origins.
You can think of CORS interactions as an apartment building with Security. For example, if you need to borrow a ladder, you could ask a neighbor in your building who has one. Security would likely not have a problem with this request (that is, same-origin, your building). If you needed a particular tool, however, and you ordered it delivered from an online hardware store (that is, cross-origin, another site), Security may request identification before allowing the delivery man into the apartment building. (Credit: Codecademy)
The way you configure CORs depends on which company you use to host your web application. The application generator adds a `cors` directory to your application scaffolding. This directory contains files for Netlify (`_headers` and `_redirects`) as well as one for Firebase (`firebase.json`). The configurations in the `cors` directory make your application's `manifest.json` file accessible to other applications (for example, to the Stacks Browser). If you are deploying to a service other than Netlify or Firebase, you must configure CORS on that service to include the following headers when serving `manifest.json`:
````html
Access-Control-Allow-Origin: * Access-Control-Allow-Headers: "X-Requested-With, Content-Type,
Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding" Access-Control-Allow-Methods:
"POST, GET, OPTIONS, DELETE, PUT"```
````
Consult the documentation for your hosting service to learn how to configure CORS on that service.
## Deployment and Radiks
If you are deploying a Stacks application that uses Radiks, your deployment includes a server and a database component. You must take this into account when deploying your application. You may want to choose a service such as Heroku or Digital Ocean if your app uses Radiks.

24
src/pages/es/references/faqs.md

@ -0,0 +1,24 @@
---
title: FAQs
description: Find answers related to the Stacks ecosystem.
---
## General Information
Learn more about the user-owned internet on Bitcoin and the Stacks ecosystem on [stacks.co](https://stacks.co).
## Apps and Smart Contracts
Developers, get started building apps and contracts on the [developer page at stacks.co](https://www.stacks.co/developers).
## Stacks Network
Learn more about the network behind the user-owned internet on Bitcoin in the [Understand Stacks chapter](/understand-stacks/overview) in the docs.
## Stacks Token
Stacks fuel apps and smart contracts on Bitcoin. Learn more at [stackstoken.com](https://stackstoken.com/faq).
## Stacks Wallet
Download and find resources about the Stacks Wallet by Hiro at [hiro.so](https://www.hiro.so/wallet).

8
src/pages/es/references/glossary.md

@ -0,0 +1,8 @@
---
title: Glossary
description: A comprehensive list of terms used within the ecosystem.
---
export { convertGlossaryToJson as getStaticProps } from '@common/data/glossary'; import { Glossary } from '@components/glossary';
<Glossary data={props.glossary} />

10
src/pages/es/references/language-functions.md

@ -0,0 +1,10 @@
---
title: Functions
description: See a detailed list of all functions for the Clarity language.
---
export { convertClarityRefToMdx as getStaticProps } from '@common/data/clarity-ref'; import { ClarityFunctionReference } from '@components/clarity-ref';
## Function reference
<ClarityFunctionReference {...props.mdx.functions} />

10
src/pages/es/references/language-keywords.md

@ -0,0 +1,10 @@
---
title: Keywords
description: See a detailed list of all keywords for the Clarity language.
---
export { convertClarityRefToMdx as getStaticProps } from '@common/data/clarity-ref'; import { ClarityKeywordReference } from '@components/clarity-ref';
## Keyword reference
<ClarityKeywordReference {...props.mdx.keywords} />

84
src/pages/es/references/language-overview.md

@ -0,0 +1,84 @@
---
title: Overview
description: Overview of the Clarity language constructs
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
export { convertClarityRefToMdx as getStaticProps } from '@common/data/clarity-ref'; import { ClarityKeywordReference, ClarityFunctionReference } from '@components/clarity-ref';
## Clarity Type System
The Clarity language uses a strong static type system. Function arguments and database schemas require specified types, and use of types is checked during contract launch. The type system does _not_ have a universal super type.
## Public Functions
Functions specified via `define-public` statements are _public_ functions and these are the only types of functions which may be called directly through signed blockchain transactions. In addition to being callable directly from a transaction (see the Stacks wire formats for more details on Stacks transactions), public function may be called by other smart contracts.
Public functions _must_ return a `(response ...)` type. This is used by Clarity to determine whether or not to materialize any changes from the execution of the function. If a function returns an `(err ...)` type, and mutations on the blockchain state from executing the function (and any function that it called during execution) will be aborted.
In addition to function defined via `define-public`, contracts may expose read-only functions. These functions, defined via `define-read-only`, are callable by other smart contracts, and may be queryable via public blockchain explorers. These functions _may not_ mutate any blockchain state. Unlike normal public functions, read-only functions may return any type.
## Contract Calls
A smart contract may call functions from other smart contracts using a `(contract-call?)` function.
This function returns a response type result-- the return value of the called smart contract function.
We distinguish 2 different types of `contract-call?`:
### Static dispatch
The callee is a known, invariant contract available on-chain when the caller contract is deployed. In this case, the callee's principal is provided as the first argument, followed by the name of the method and its arguments:
```clarity
(contract-call?
.registrar
register-name
name-to-register)
```
### Dynamic dispatch
The callee is passed as an argument, and typed as a trait reference (`<A>`).
```clarity
(define-public (swap (token-a <can-transfer-tokens>)
(amount-a uint)
(owner-a principal)
(token-b <can-transfer-tokens>)
(amount-b uint)
(owner-b principal)))
(begin
(unwrap! (contract-call? token-a transfer-from? owner-a owner-b amount-a))
(unwrap! (contract-call? token-b transfer-from? owner-b owner-a amount-b))))
```
Traits can either be locally defined:
```clarity
(define-trait can-transfer-tokens (
(transfer-from? (principal principal uint) (response uint)))
```
Or imported from an existing contract:
```clarity
(use-trait can-transfer-tokens
.contract-defining-trait.can-transfer-tokens)
```
Looking at trait conformance, callee contracts have two different paths. They can either be "compatible" with a trait by defining methods matching some of the methods defined in a trait, or explicitely declare conformance using the `impl-trait` statement:
```clarity
(impl-trait .contract-defining-trait.can-transfer-tokens)
```
Explicit conformance should be prefered when adequate. It acts as a safeguard by helping the static analysis system to detect deviations in method signatures before contract deployment.
The following limitations are imposed on contract calls:
1. On static dispatches, callee smart contracts _must_ exist at the time of creation.
2. No cycles may exist in the call graph of a smart contract. This prevents recursion (and re-entrancy bugs). Such structures can be detected with static analysis of the call graph, and will be rejected by the network.
3. `contract-call?` are for inter-contract calls only. Attempts to execute when the caller is also the callee will abort the transaction.

23
src/pages/es/references/language-types.md

@ -0,0 +1,23 @@
---
title: Types
description: See a detailed list of all types for the Clarity language.
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Clarity Type System
The type system contains the following types:
- `{label-0: value-type-0, label-1: value-type-1, ...}` - a group of data values with named fields, aka (_record_)[https://www.cs.cornell.edu/courses/cs312/2004fa/lectures/lecture3.htm].
- `(list max-len entry-type)` - a list of maximum length `max-len`, with entries of type `entry-type`
- `(response ok-type err-type)` - object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior.
- `(optional some-type)` - an option type for objects that can either be `(some value)` or `none`
- `(buff max-len)` := byte buffer of maximum length `max-len`.
- `(string-ascii max-len)` := ASCII string of maximum length `max-len`
- `(string-utf8 max-len)` := UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string")
- `principal` := object representing a principal (whether a contract principal or standard principal).
- `bool` := boolean value (`true` or `false`)
- `int` := signed 128-bit integer
- `uint` := unsigned 128-bit integer

24
src/pages/es/references/stacking-contract.md

@ -0,0 +1,24 @@
---
title: Stacking Contract
description: See a detailed list of all functions and error codes of the Stacking contract.
---
export { convertStackingRefToMdx as getStaticProps } from '@common/data/stacking-ref'; import { StackingErrorcodeReference, StackingFunctionReference } from '@components/stacking-ref';
## Introduction
Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info).
Below is a list of public and read-only functions as well as error codes that can be returned by those methods.
## Public functions
<StackingFunctionReference {...props.mdx.publicFunctions} />
## Read-only functions
<StackingFunctionReference {...props.mdx.readonlyFunctions} />
## Error codes
<StackingErrorcodeReference {...props.mdx.errorCodes} />

513
src/pages/es/references/stacks-node-configuration.md

@ -0,0 +1,513 @@
---
title: Stacks Node Configuration
description: Configuration parameters and options for the stacks-node binary
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Usage
```bash
stacks-node sub-command [--subcommand-option <value>]
```
## Subcommands
-> Note that the `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources.
### mocknet
Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development.
Example:
```bash
stacks-node mocknet
```
### krypton
Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](/understand-stacks/overview#proof-of-transfer-pox).
Example:
```bash
stacks-node krypton
```
### xenon
Start a node that will join and stream blocks from the public xenon testnet.
Example:
```bash
stacks-node xenon
```
### mainnet
Start a node that joins and streams blocks from the public mainnet.
Example:
```bash
stacks-node mainnet
```
### start
Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `xenon` subcommands.
#### Arguments
**--config**: relative or absolute path to the TOML config file. Required.
Example:
```bash
stacks-node start --config=/path/to/config.toml
```
See [Configuration File Options](#configuration-file-options) for more information.
#### version
Displays information about the current version and the release cycle.
Example:
```bash
stacks-node version
```
#### help
Displays a help message.
Example:
```bash
stacks-node help
```
## Configuration File Options
The TOML configuration file has multiple sections under which an option may be placed.
To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf).
### Section: node
Contains various configuration options pertaining to the stacks-node.
Example:
```toml
[node]
rpc_bind = "0.0.0.0:20443"
p2p_bind = "0.0.0.0:20444"
# Enter your private key here
seed = "replace-with-your-private-key"
miner = true
```
#### working_dir (optional)
Absolute path to the directory which the stacks-node will use for storing various data.
Example:
```toml
working_dir = "/root/stacks-node"
```
#### rpc_bind
Address and port stacks-node should bind to for RPC connections.
Example:
```toml
rpc_bind = "0.0.0.0:20443"
```
#### p2p_bind
Address and port stacks-node should bind to for P2P connections.
Example:
```toml
p2p_bind = "0.0.0.0:20444"
```
#### data_url (optional)
Address and port from which the stacks-node will be receiving incoming rpc connections.
Example:
```toml
data_url = "1.2.3.4:20443"
```
#### p2p_address (optional)
Address and port from which the stacks-node will be receiving incoming p2p connections.
Example:
```toml
p2p_address = "1.2.3.4:20444"
```
#### bootstrap_node (optional)
Public key, address, and port stacks-node should use to pull transaction data from when starting.
Example:
```toml
bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@xenon.blockstack.org:20444"
```
#### wait_time_for_microblocks (optional)
The amount of time (in milliseconds) that a node will wait before trying to mine a block, after catching up to the anchored chain tip. This gives the current leader time to broadcast microblocks that will get included in that mined block.
Example:
```toml
wait_time_for_microblocks = 15000
```
#### seed (optional)
The private key to use for mining. Only needed if `miner` is set to `true`.
[See this page for information on how to generate a private key.](/start-mining)
Example:
```toml
seed = "replace-with-your-private-key"
```
#### local_peer_seed (optional)
The private key to use for signing P2P messages in the networking stack. It differentiates network peers and is used even by non-mining nodes.
[See this page for information on how to generate a private key.](/start-mining)
Example:
```toml
local_peer_seed = "replace-with-your-private-key"
```
#### miner (optional)
Determines whether the stacks-node is running a follower (`false`) or a miner (`true`). Defaults to `false` if omitted.
[See this page for information on how to run a miner.](/start-mining)
Example:
```toml
miner = true
```
#### mine_microblocks (optional)
Determines whether the stacks-node will mine microblocks. Will only take effect if `miner` is set to `true`.
[See this page for information on how to run a miner.](/start-mining)
Example:
```toml
mine_microblocks = true
```
#### prometheus_bind (optional)
Address and port stacks-node should open for Prometheus metrics collection.
Example:
```toml
prometheus_bind = "0.0.0.0:9153"
```
### Section: events_observer (optional)
Contains options for watching events emitted by a local [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service.
-> This section can be repeated multiple times.
Example:
```toml
[[events_observer]]
endpoint = "address-to-my-local.stacks-node-api.com:3700"
retry_count = 255
events_keys = ["*"]
```
#### endpoint
Address and port to a stacks-node-api to watch for events.
Example:
```toml
endpoint = "address-to-my-local.stacks-node-api.com:3700"
```
#### retry_count
Number of times to retry sending events to the endpoint before failing.
Example:
```toml
retry_count = 255
```
#### events_keys
Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events.
Examples:
```toml
events_keys = ["*"]
```
```toml
events_keys = [
"STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.store::print",
"STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.contract.ft-token",
"STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.contract.nft-token",
"stx"
]
```
### Section: connection_options (optional)
Specifies configuration options for others connecting to the stacks node.
Example:
```toml
[connection_options]
public_ip_address = "1.2.3.4:20444"
download_interval = 60
walk_interval = 30
```
#### public_ip_address
The advertised public IP of this stacks-node.
Example:
```toml
public_ip_address = "1.2.3.4:20444"
```
#### download_interval
Time (in seconds) between attempts to download blocks.
Example:
```toml
download_interval = 60
```
#### walk_interval
Time (in seconds) between attempts to walk the neighborhood.
Example:
```toml
walk_interval = 30
```
#### read_only_call_limit_read_length
Total number of bytes allowed to be read by an individual read-only function call.
Example:
```toml
read_only_call_limit_read_length = 100000
```
#### read_only_call_limit_read_count
Total number of independent read operations permitted for an individual read-only function call.
Example:
```toml
read_only_call_limit_read_count = 30
```
#### read_only_call_limit_runtime
[Runtime cost](https://github.com/stacksgov/sips/blob/2d3fd9bf8da7a04f588d90ff6252173d7609d7bf/sips/sip-006/sip-006-runtime-cost-assessment.md#introduction) limit for an individual read-only function call.
Example:
```toml
read_only_call_limit_runtime = 1000000000
```
### Section: burnchain
This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC).
Example:
```toml
[burnchain]
chain = "bitcoin"
mode = "mainnet"
peer_host = "your.bitcoind.node.org"
rpc_port = 8332
peer_port = 8333
```
#### chain
The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `"bitcoin"`.
Example:
```toml
chain = "bitcoin"
```
#### mode
The profile or test phase of which to run stacks-node. Valid values are `"mocknet"`, `"helium"`, `"neon"`, `"argon"`, `"krypton"`, `"xenon"`.
Example:
```toml
mode = "xenon"
```
#### peer_host
Domain name of the host running the backend Bitcoin blockchain. It's required to either run a personal Bitcoin node locally, or to use a publicly hosted Bitcoin node.
Example:
```toml
peer_host = "your.bitcoind.node.org"
```
#### rpc_port
peer_host's port stacks-node will connect to for RPC connections.
Example:
```toml
rpc_port = 8332
```
#### peer_port
peer_host's port stacks-node will connect to for P2P connections.
Example:
```toml
peer_port = 8333
```
#### burn_fee_cap (optional)
Maximum amount (in Satoshis) of "burn commitment" to broadcast for the next block's leader election.
Example:
```toml
burn_fee_cap = 30000
```
#### satoshis_per_byte (optional)
Amount (in Satoshis) per [virtual byte](https://en.bitcoin.it/wiki/Weight_units). This is used to compute the transaction fees.
Example:
```toml
satoshis_per_byte = 50
```
So total transaction cost would be `(estimated_tx_size * satoshis_per_byte) + burn_fee_cap`.
#### commit_anchor_block_within (optional)
Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `"helium"`.
Example:
```toml
commit_anchor_block_within = 10000
```
### Section: ustx_balance (testnet/regtest only)
This section contains configuration options pertaining to the genesis block allocation for an address in micro-STX. If a user changes these values, their node may be in conflict with other nodes on the network and find themselves unable to sync with other nodes.
-> This section can repeat multiple times, and thus is in double-brackets. Each section can define only one address. This section is ignored if running a node on mainnet.
Example:
```toml
[[ustx_balance]]
address = "STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6"
amount = 10000000000000000
[[ustx_balance]]
address = "ST11NJTTKGVT6D1HY4NJRVQWMQM7TVAR091EJ8P2Y"
amount = 10000000000000000
[[ustx_balance]]
address = "ST1HB1T8WRNBYB0Y3T7WXZS38NKKPTBR3EG9EPJKR"
amount = 10000000000000000
[[ustx_balance]]
address = "STRYYQQ9M8KAF4NS7WNZQYY59X93XEKR31JP64CP"
amount = 10000000000000000
```
#### address
Address which maintains a micro-STX balance.
Example:
```toml
address = "STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6"
```
#### amount
The balance of micro-STX given to the address at the start of the node.
Example:
```toml
amount = 10000000000000000
```

352
src/pages/es/start-mining/mainnet.md

@ -0,0 +1,352 @@
---
title: Mine mainnet Stacks tokens
description: Set up and run a miner on the Stacks 2.0 mainnet
icon: MainnetIcon
experience: beginners
duration: 10 minutes
tags:
- tutorial
images:
large: /images/pages/start-mining.svg
sm: /images/pages/start-mining-sm.svg
---
## Introduction
Make sure you've followed the [Running mainnet node](/understand-stacks/running-mainnet-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet.
If you're interested in mining on the testnet, you can find instructions on how to do that here:
[@page-reference | inline] | /start-mining/testnet
If you want to learn more about the technical details of mining, please review the mining guide:
[@page-reference | inline] | /understand-stacks/mining
## Running bitcoind locally
To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements)
First, download the bitcoind software for your platform from https://bitcoin.org/en/download.
Next, start bitcoind with the following configuration:
```toml
server=1
rpcuser=your-bitcoind-username
rpcpassword=your-bitcoind-password
txindex=0
listen=1
rpcserialversion=0
maxorphantx=1
banscore=1
bind=0.0.0.0:8333
rpcbind=0.0.0.0:8332
rpcport=8332
```
Finally, start bitcoind as follows:
```bash
bitcoind -conf=path/to/bitcoin.conf
```
It may take a few days for the node to synchronize with the Bitcoin mainnet.
## Running a miner
First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command.
```bash
npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt
```
After this runs, you should see some JSON in the new `keychain.txt` file that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
**Don't lose this information** - we'll need to use the `privateKey` field later on.
The above BTC address will then need to be imported into the BTC network.
```bash
bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress <btcAddress from JSON above>
```
Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
# Enter your private key here
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on mainnet, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file.
To run your miner, run this in the command line:
```bash
stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml
```
Your node should start. It will take some time to sync, and then your miner will be running.
### Creating an optimized binary
The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run:
```bash
cd testnet/stacks-node
cargo build --release --bin stacks-node
```
The above code will compile an optimized binary. To use it, run:
```bash
cd ../..
./target/release/stacks-node start --config=./mainnet-miner-conf.toml
```
For a full reference of subcommands and configuration options used by `stacks-node`, please see this page.
[@page-reference | inline] | /references/stacks-node-configuration
To read more about the technical details of mining on the Stacks 2.0 network, have a look at the minig guide:
[@page-reference | inline] | /understand-stacks/mining
### Enable debug logging
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
STACKS_LOG_DEBUG=1 stacks-node mainnet
```
## Running a miner in Windows
### Prerequisites
Make sure you've followed the [Running the mainnet node on Windows](/understand-stacks/running-mainnet-node#running-the-mainnet-node-on-windows) tutorial and [Running itcoind locally](#running-bitcoind-locally) section above before starting this tutorial.
### Generate keychain and get mainnet tokens in Windows
To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command.
Generate a keychain:
```bash
npm install --global @stacks/cli
stx make_keychain > cli_keychain.json
type cli_keychain.json
```
After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
-> Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details
The above BTC address will then need to be imported into the BTC network.
```bash
bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress <btcAddress from JSON above>
```
Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
### Update configuration file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
# Enter your private key here
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on mainnet, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Run the miner
To start your miner, run this in the command line:
```bash
stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml
```
-> **Note** : While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. ![Windows Defender](/images/windows-defender.png)
Your node should start. It will take some time to sync, and then your miner will be running.
### Enable debug logging in Windows
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
set RUST_BACKTRACE=full;
set STACKS_LOG_DEBUG=1;
stacks-node start --config=mainnet-miner-conf.toml
```
## Optional: Running with Docker
Alternatively, you can run the mainnet node with Docker.
-> Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine.
### Generate keychain and get tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null
```
We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
### Update configuration file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
# Enter your private key here
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on mainnet, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Start the miner
-> The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled
```bash
docker run -d \
--name stacks_miner \
--rm \
--network host \
-e RUST_BACKTRACE="full" \
-e STACKS_LOG_DEBUG="1" \
-v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain:latest \
/bin/stacks-node start --config /src/stacks-node/mainnet-miner-conf.toml
```
You can review the node logs with this command:
```bash
docker logs -f stacks_miner
```
## Optional: Running in Kubernetes with Helm
In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).
Ensure you have the following prerequisites installed on your machine:
- [Docker](https://docs.docker.com/get-docker/)
- [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster)
- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)
- [helm](https://helm.sh/docs/intro/install/)
### Generate keychain and get some tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null
```
We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
### Install the chart and run the miner
To install the chart with the release name `my-release` and run the node as a miner:
```bash
minikube start # Only run this if standing up a local Kubernetes cluster
helm repo add blockstack https://charts.blockstack.xyz
helm install my-release blockstack/stacks-blockchain \
--set config.node.miner=true \
--set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \
--set config.burnchain.mode="mainnet"
```
You can review the node logs with this command:
```bash
kubectl logs -l app.kubernetes.io/name=stacks-blockchain
```
For more information on the Helm chart and configuration options, please refer to the [chart's homepage](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).

343
src/pages/es/start-mining/testnet.md

@ -0,0 +1,343 @@
---
title: Mine testnet Stacks tokens
description: Set up and run a miner on the Stacks 2.0 testnet
icon: TestnetIcon
experience: beginners
duration: 10 minutes
tags:
- tutorial
images:
large: /images/pages/start-mining.svg
sm: /images/pages/start-mining-sm.svg
---
## Introduction
Make sure you've followed the [Running testnet node](/understand-stacks/running-testnet-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet.
If you want to learn more about the technical details of mining, please review the mining guide:
[@page-reference | inline] | /understand-stacks/mining
## Running bitcoind locally
To participate as a miner on Xenon, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements)
First, download the bitcoind software for your platform from https://bitcoin.org/en/download.
Next, start bitcoind with the following configuration:
```toml
server=1
rpcuser=your-bitcoind-username
rpcpassword=your-bitcoind-password
testnet=1
txindex=0
listen=1
rpcserialversion=0
maxorphantx=1
banscore=1
[test]
bind=0.0.0.0:18333
rpcbind=0.0.0.0:18332
rpcport=18332
```
Finally, start bitcoind as follows:
```bash
bitcoind -conf=path/to/bitcoin.conf
```
It may take a few hours for the node to synchronize with the Bitcoin testnet.
## Running a miner
First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command, and pass `-t` to indicate that we want a testnet keychain.
```bash
npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt
```
After this runs, you should see some JSON in the new `keychain.txt` file that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
**Don't lose this information** - we'll need to use the `privateKey` field later on.
The above BTC address will then need to be imported into the BTC testnet network.
```bash
bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress <btcAddress from JSON above>
```
Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address.
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on Xenon, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file.
To run your miner, run this in the command line:
```bash
stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml
```
Your node should start. It will take some time to sync, and then your miner will be running.
### Creating an optimized binary
The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run:
```bash
cd testnet/stacks-node
cargo build --release --bin stacks-node
```
The above code will compile an optimized binary. To use it, run:
```bash
cd ../..
./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml
```
For a full reference of subcommands and configuration options used by `stacks-node`, please see this page.
[@page-reference | inline] | /references/stacks-node-configuration
To read more about the technical details of mining on the Stacks 2.0 network, have a look at the minig guide:
[@page-reference | inline] | /understand-stacks/mining
### Enable debug logging
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
STACKS_LOG_DEBUG=1 stacks-node xenon
```
## Running a miner in Windows
### Prerequisites
Make sure you've followed the [Running the testnet node on Windows](/understand-stacks/running-testnet-node#running-the-testnet-node-on-windows) tutorial before starting this tutorial.
### Generate keychain and get testnet tokens in Windows
To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain.
Generate a keychain:
```bash
npm install --global @stacks/cli
stx make_keychain -t > cli_keychain.json
type cli_keychain.json
```
After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
-> Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details
Request BTC from faucet:
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address.
### Update configuration file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on Xenon, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Run the miner
To start your miner, run this in the command line:
```bash
stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml
```
-> **Note** : While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. ![Windows Defender](/images/windows-defender.png)
Your node should start. It will take some time to sync, and then your miner will be running.
### Enable debug logging in Windows
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
set RUST_BACKTRACE=full;
set STACKS_LOG_DEBUG=1;
stacks-node start --config=testnet-miner-conf.toml
```
## Optional: Running with Docker
Alternatively, you can run the testnet node with Docker.
-> Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine.
### Generate keychain and get testnet tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null
```
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address.
### Update config file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on Xenon, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Start the miner
-> The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled
```bash
docker run -d \
--name stacks_miner \
--rm \
--network host \
-e RUST_BACKTRACE="full" \
-e STACKS_LOG_DEBUG="1" \
-v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain:latest \
/bin/stacks-node start --config /src/stacks-node/testnet-miner-conf.toml
```
You can review the node logs with this command:
```bash
docker logs -f stacks_miner
```
## Optional: Running in Kubernetes with Helm
In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).
Ensure you have the following prerequisites installed on your machine:
- [Docker](https://docs.docker.com/get-docker/)
- [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster)
- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)
- [helm](https://helm.sh/docs/intro/install/)
### Generate keychain and get some testnet tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null
```
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address.
### Install the chart and run the miner
To install the chart with the release name `my-release` and run the node as a miner:
```bash
minikube start # Only run this if standing up a local Kubernetes cluster
helm repo add blockstack https://charts.blockstack.xyz
helm install my-release blockstack/stacks-blockchain \
--set config.node.miner=true \
--set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step"
```
You can review the node logs with this command:
```bash
kubectl logs -l app.kubernetes.io/name=stacks-blockchain
```
For more information on the Helm chart and configuration options, please refer to the [chart's homepage](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).

211
src/pages/es/understand-stacks/accounts.md

@ -0,0 +1,211 @@
---
title: Accounts
description: Guide to Stacks 2.0 accounts
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Introduction
Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances.
If you want to jump right in to generate and query a new account, try this tutorial:
-> The public-key signature system used for Stacks 2.0 accounts is [Ed25519](https://ed25519.cr.yp.to/).
Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction.
-> The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account
## Creation
An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts.
!> If the seed phrase is lost, access to the associated account cannot be restored. No person or organization, including Blockstack, can recover a lost seed phrase.
The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli):
```bash
# install CLI globally
npm install --global @stacks/cli
# generate a new account and store details in a new file
# '-t' option makes this a testnet account
stx make_keychain -t > cli_keychain.json
```
`make_keychain` creates the following file:
```js
{
"mnemonic": "aaa bbb ccc ddd ...",
"keyInfo": {
"privateKey": "5a3f1f15245bb3fb...",
"address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1",
"btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1",
"wif": "L4HXn7PLmzoNW...",
"index": 0
}
}
```
-> Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details
| Field | Description |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy |
| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` |
| `keyInfo.address` | Stacks address for the account |
| `keyInfo.btcAddress` | Corresponding BTC address for the account. |
| `keyInfo.wif` | Private key of the btcAddress in compressed format. |
| `keyInfo.index` | Nonce for the account, starting at 0 |
Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain.
-> Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method.
Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used:
```js
import {
makeRandomPrivKey,
privateKeyToString,
getAddressFromPrivateKey,
TransactionVersion,
} from '@stacks/transactions';
const privateKey = makeRandomPrivKey();
// Get public key from private
const publicKey = getPublicKey(privateKey);
const stacksAddress = getAddressFromPrivateKey(
privateKeyToString(privateKey),
TransactionVersion.Testnet // remove for Mainnet addresses
);
```
A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`.
#### stacks-gen prerequisite
Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `<command>` exists in \$PATH, or in the local project binaries, and execute that. If `<command>` is not found, it will be installed prior to execution).
```
npm install -g npx
```
#### stacks-gen usage
```
npx -q stacks-gen sk --testnet
{
"phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef",
"private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901",
"public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662",
"stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C",
"stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }",
"btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8",
"wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh"
}
```
-> The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](/understand-stacks/stacking#bitcoin-address).
Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen).
## Querying
### Get Stacks (STX) balance and nonce
STX balance and nonce can be obtained through the [`GET /v2/accounts/<stx_address>`](https://docs.hiro.so/api#operation/get_account_info) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/<stx_address>'
```
Sample response:
```js
{
"balance": "0x0000000000000000002386f26f3f40ec",
"nonce": 17
}
```
-> The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding
### Get all token balances
All token balances can be obtained through the [`GET /extended/v1/address/<stx_address>/balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address/<stx_address>/balances'
```
Sample response:
```js
{
"stx": {
"balance": "0",
"total_sent": "0",
"total_received": "0"
},
"fungible_tokens": {},
"non_fungible_tokens": {}
}
```
-> Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network.
### Get all asset events
All asset events associated with the account can be obtained through the [`GET /extended/v1/address/<stx_address>/assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address/<stx_address>/assets'
```
Sample response:
```js
{
"limit": 20,
"offset": 0,
"total": 0,
"results": [
{
"event_index": 5,
"event_type": "non_fungible_token_asset",
"asset": {
"asset_event_type": "transfer",
"asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft",
"sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR",
"recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G",
"value": {
"hex": "0x0100000000000000000000000000000001",
"repr": "u1"
}
}
},
{
"event_index": 3,
"event_type": "fungible_token_asset",
"asset": {
"asset_event_type": "mint",
"asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19",
"sender": "",
"recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR",
"amount": "12"
}
}
]
}
```

110
src/pages/es/understand-stacks/microblocks.md

@ -0,0 +1,110 @@
---
title: Microblocks
description: Guide to Stacks Microblocks
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Introduction
Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism][], Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks.
Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin.
## Transaction states
The [Stacks block production model][] is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model.
If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known.
Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle:
```
Transaction 1 is broadcast to the mempool. It has 0 confirmations.
Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known
Transaction 1 is included in the next anchor block. It has 1 confirmation.
The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations.
The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations.
...
```
Consider a similar transaction that is not included in a microblock:
```
Transaction 2 is broadcast to the mempool. It has 0 confirmations.
Transaction 2 is included in the next anchor block. It has 1 confirmation.
The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations.
The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations.
```
The lifecycles of the two transactions are similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information.
-> If a transaction is dependent on a chain state that could by altered by previous transactions with serious implications, you should carefully consider whether it should be performed using microblocks.
## Enabling microblocks
Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either.
### Transactions
Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either.
### Mining
Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks][].
## Developing with microblocks
In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative.
A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred.
### Stacks.js libraries
Stacks.js provides the [AnchorMode][] argument on transaction objects so that your application can set the microblocks preference for transactions.
### API
!> API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks.
The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide][] for more details.
## Best practices
Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended.
### Handling nonce
Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal.
### Application design
The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this.
The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application.
#### Explorers
Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state.
#### Wallets
Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state.
#### Exchanges
Continue to count confirmations, microblocks should be considered pending.
#### Applications
Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed.
[Proof-of-Transfer consensus mechanism]: /understand-stacks/proof-of-transfer
[Stacks block production model]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader
[mining microblocks]: /understand-stacks/mining#microblocks
[AnchorMode]: https://stacks-js-git-master-blockstack.vercel.app/enums/transactions.anchormode.html
[Stacks Blockchain API guide]: https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support
[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling
[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks

74
src/pages/es/understand-stacks/mining.md

@ -0,0 +1,74 @@
---
title: Mining
description: A guide to mining on Stacks 2.0
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Introduction
This guide highlights some technical details related to mining on the Stacks 2.0 network.
## Mining frequency
A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee.
## Coinbase rewards
Miners receive coinbase rewards for blocks they win.
The reward amounts are:
- 1000 STX per block are released in the first 4 years of mining
- 500 STX per block are released during the following 4 years
- 250 STX per block are released during the following 4 years
- 125 STX per block are released from then on indefinitely.
These "halvings" are synchronized with Bitcoin halvings.
![coinbase rewards](/images/pages/coinbase-rewards.png)
## Transaction fees
Miners receive Stacks fees for transactions mined in any block they produce.
For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees.
## Reward maturity
Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours.
## Mining with proof-of-transfer
Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain.
![mining with pox](/images/pages/mining-with-pox.png)
100,000 Bitcoin blocks **after** mining begins, the PoX sunset phase begins. During this phase, an increasing proportion of the block commit must be burnt. To burn this sunset fee, the miner must send the sunset fee amount to the first output of their block commit transaction (that is, the OPRETURN output).
400,000 Bitcoin blocks after the sunset phase begins, the sunset phase ends. After this point, PoX is no longer active, and miners must burn all of their leader block commits. They do so by sending Bitcoin to the canonical burn address `1111111111111111111114oLvT2`.
## Probability to mine next block
The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt.
The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent.
While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended.
To calculate the amount of BTC to send miners should:
- Guess the price BTC/STX for the next day (100 blocks later)
- Guess the total amount of BTCs committed by all miners
## Microblocks
The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch.
If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces.
The block streaming model is described in [SIP-001][].
[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader

147
src/pages/es/understand-stacks/network.md

@ -0,0 +1,147 @@
---
title: Network
description: Guide to the Stacks 2.0 network
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Tokens
Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX).
STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6).
## Fees
Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](/understand-stacks/testnet), it is set to 1 micro-STX.
Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer'
```
The API will respond with the fee rate (as integer):
```json
1
```
[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for:
- token transfers (`estimateTransfer`)
- contract deploys (`estimateContractDeploy`)
- non read-only contract calls (`estimateContractFunctionCall`)
-> For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97).
## Nonces
Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction.
Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing.
-> The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers.
When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set.
-> The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling).
## Confirmations
The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain.
The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes.
-> Transactions can also be mined in [microblocks](/understand-stacks/microblocks), reducing the latency significantly.
The block time is hardcoded and will change throughout the implementation phases of the [testnet](/understand-stacks/testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times'
```
The API will respond with the block time (in seconds):
```js
{
"testnet": {
"target_block_time": 120
},
"mainnet": {
"target_block_time": 600
}
}
```
## Read-only function calls
Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted.
However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api).
-> Read-only function calls do not require transaction fees
A read-only contract call can be done using the [`POST /v2/contracts/call-read/<stx_address>/<contract_name>/<function_name>`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read/<stx_address>/<contract_name>/<function_name>' \
--header 'Content-Type: application/json' \
--data-raw '{
"sender": "<stx_address>.<contract_name>",
"arguments": [<clarity_value>, ...]
}'
```
Sample response for a successful call:
```js
{
"okay": true,
"result": "<clarity_value>"
}
```
-> To set the function call arguments and read the result, [Clarity values](/write-smart-contracts/values) need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations
## Querying
Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api).
### Health check
The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain.
### Network info
The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/v2/info'
```
Sample response:
```js
{
"peer_version": 385875968,
"burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37",
"burn_block_height": 1972,
"stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64",
"stable_burn_block_height": 1971,
"server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]",
"network_id": 2147483648,
"parent_network_id": 3669344250,
"stacks_tip_height": 933,
"stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f",
"stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc",
"unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae",
"exit_at_block_height": 28160
}
```

70
src/pages/es/understand-stacks/overview.md

@ -0,0 +1,70 @@
---
title: Overview
description: Learn more about the Stacks 2.0 blockchain
icon: TestnetIcon
images:
large: /images/nodes.svg
sm: /images/nodes.svg
---
## Introduction
Stacks 2.0 is a layer-1 blockchain that connects to Bitcoin and brings smart contracts and decentralized apps to it. Smart contracts and apps developed on the Stacks platform are natively integrated with the security, stability, and economic power of Bitcoin.
## Capabilities
Read more about the features provided by the Stacks 2.0 blockchain.
-> Check out the [technical specifications](/understand-stacks/technical-specs) for a brief overview
A detailed [comparison of the Stacks blockchain to other blockchain technologies][] is available at the Stacks Foundation blog.
### Consensus mechanism
Stacks 2.0 implements a new mining mechanism called Proof of Transfer ("PoX"). PoX is a consensus algorithm between two blockchains. It uses an established blockchain (in this case Bitcoin) to secure a new blockchain (Stacks).
PoX connects to Bitcoin with a 1:1 block ratio, meaning anything that happens on the Stacks blockchain can be verified on the Bitcoin Blockchain.
Instead of burning electricity on proof of work, PoX reuses already minted bitcoins as "proof of computation" and miners represent their cost of mining in bitcoins directly.
[@page-reference | inline] | /understand-stacks/proof-of-transfer
### Mining
Mining is required to make the network usable, trustworthy, and secure. Miners verify incoming transactions, participate in the consensus mechanism, and write new blocks to the blockchain.
To incentivize mining, miners receive freshly minted Stacks (STX) tokens if they win the bid for becoming the leader of the next round.
[@page-reference | inline] | /understand-stacks/mining
### Stacking
Bitcoins used for miner bids are sent to a set of specific addresses corresponding to Stacks (STX) tokens holders that are actively participating in consensus ("Stackers"). Thus, rather than being destroyed, the bitcoins consumed in the mining process go to productive Stacks holders as a reward based on their holdings of Stacks and participation in the Stacking algorithm.
Stackers have to lock up their Stacks (STX) tokens for a certain period of time.
[@page-reference | inline] | /understand-stacks/stacking
### Smart contracts
Clarity is a new language for smart contracts on the Stacks 2.0 blockchain. The Clarity smart contract language optimizes for predictability and security.
Stacks 2.0 anchors clarity smart contracts to Bitcoin making it possible for smart contracts to operate based on actions seen on the bitcoin blockchain.
-> The [Clarity open-source project](https://clarity-lang.org/) is supported by Stacks and [Algorand](https://www.algorand.com/)
Clarity is distinct from other languages designed for writing smart contracts in a few ways:
- **Predictability**: The Clarity language uses precise and unambiguous syntax that allows developers to predict exactly how their contracts will be executed.
- **Security**: The Clarity language allows users to supply their own conditions for transactions that ensure that a contract may never unexpectedly transfer a token owned by a user.
- **No compiler**: Contracts written in Clarity are broadcasted on the Stacks blockchain exactly as they are written by developers. This ensures that the code developers wrote, analyzed, and tested, is exactly what gets executed.
[@page-reference | inline] | /write-smart-contracts/overview
## Guides
Read one of our guides to understand the ins and outs of the Stacks 2.0 blockchain.
[@page-reference | grid-small] | /understand-stacks/accounts, /understand-stacks/transactions, /understand-stacks/network, /understand-stacks/microblocks
[comparison of the Stacks blockchain to other blockchain technologies]: https://stacks.org/stacks-blockchain

57
src/pages/es/understand-stacks/proof-of-transfer.md

@ -0,0 +1,57 @@
---
title: Proof of Transfer
description: Understand the proof-of-transfer consensus mechanism
icon: TestnetIcon
images:
large: /images/stacking.svg
sm: /images/stacking.svg
---
## Overview
Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network.
Popular consensus mechanisms in modern blockchains include proof-of-work, in which nodes dedicate computing resources, and proof-of-stake, in which nodes dedicate financial resources to secure the network.
Proof-of-burn is a novel consensus mechanism where miners compete by ‘burning’ (destroying) a proof-of-work cryptocurrency as a proxy for computing resources.
Proof-of-transfer (PoX) is an extension of the proof-of-burn mechanism. PoX uses the proof-of-work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof-of-burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network.
![PoX mechanism](/images/pox-mechanism.png)
This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, proof-of-transfer blockchains are anchored on their chosen proof-of-work chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain.
![PoX participants](/images/pox-participants.png)
## Why Bitcoin?
There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade.
Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the proof-of-transfer consensus mechanism.
SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md).
![btc-stacks](/images/pox-why-bitcoin.png)
## Blocks and microblocks
The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network.
However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin.
![stx-microblock](/images/stx-microblocks.png)
## Unlocking Bitcoin capital
Stacks also unlocks the hundreds of billions in capital in Bitcoin, and gives Bitcoiners new opportunities to use and earn BTC. Stacks is a accompaniment to the Bitcoin ecosystem, and the two networks working in tandem enables totally novel ways of using BTC. The Stacks ecosystem makes interactive cryptocurrency applications available to Bitcoin holders. Additionally, By stacking STX tokens and participating in the PoX consensus mechanism, users have the opportunity to earn BTC while securing the Stacks chain.
![Unlocking Bitcoin](/images/pox-unlocking-btc.png)
## Clarity and the Bitcoin state
Clarity smart contracts also have unique visibility into the state of the Bitcoin blockchain. This means that contract logic in a Clarity file has the ability to trigger when specific Bitcoin transactions are confirmed. Clarity smart contracts have a built in Simple Payment Verification (SPV) proofs for Bitcoin that make interacting with Bitcoin’s state much simpler for developers. Additionally, Clarity contracts can fork with the original Bitcoin chain. Therefore, in an edge case where Bitcoin forks, developers wouldn’t have to worry about adjusting the deployment of their smart contracts.
## See also
- [Read the full PoX whitepaper](https://community.stacks.org/pox)
- [Watch CEO Muneeb Ali and Evangelist Joe Bender give an overview of Stack's breakthrough PoX mining mechanism](https://www.youtube.com/watch?v=NY_eUrIcWOY)

188
src/pages/es/understand-stacks/running-mainnet-node.md

@ -0,0 +1,188 @@
---
title: Running a mainnet node
description: Set up and run a mainnet node with Docker
icon: MainnetIcon
duration: 15 minutes
experience: beginners
tags:
- tutorial
images:
large: /images/pages/mainnet.svg
sm: /images/pages/mainnet-sm.svg
---
## Introduction
This procedure demonstrates how to run a local mainnet node using Docker images.
-> This procedure focuses on Unix-like operating systems (Linux and MacOS). This procedure has not been tested on Windows.
## Prerequisites
Running a node has no specialized hardware requirements. Users have been successful in running nodes on Raspberry Pi boards and other system-on-chip architectures. In order to complete this procedure, you must have the following software installed on the node host machine:
- [Docker](https://docs.docker.com/get-docker/)
- [curl](https://curl.se/download.html)
- [jq](https://stedolan.github.io/jq/download/)
### Firewall configuration
In order for the API node services to work correctly, you must configure any network firewall rules to allow traffic on the ports discussed in this section. The details of network and firewall configuration are highly specific to your machine and network, so a detailed example isn't provided.
The following ports must open on the host machine:
Ingress:
- stacks-blockchain (open to `0.0.0.0/0`):
- `20443 TCP`
- `20444 TCP`
Egress:
- `8332`
- `8333`
- `20443-20444`
These egress ports are for syncing [`stacks-blockchain`][] and Bitcoin headers. If they're not open, the sync will fail.
## Step 1: initial setup
In order to run the mainnet node, you must download the Docker images and create a directory structure to hold the persistent data from the services. Download and configure the Docker images with the following commands:
```sh
docker pull blockstack/stacks-blockchain
```
Create a directory structure for the service data with the following command:
```sh
mkdir -p ./stacks-node/{persistent-data/stacks-blockchain/mainnet,config/mainnet} && cd stacks-node
```
## Step 2: running Stacks blockchain
First, create the `./config/mainnet/Config.toml` file and add the following content to the file using a text editor:
```toml
[node]
working_dir = "/root/stacks-node/data"
rpc_bind = "0.0.0.0:20443"
p2p_bind = "0.0.0.0:20444"
bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444"
wait_time_for_microblocks = 10000
[burnchain]
chain = "bitcoin"
mode = "mainnet"
peer_host = "bitcoin.blockstack.com"
username = "blockstack"
password = "blockstacksystem"
rpc_port = 8332
peer_port = 8333
[connection_options]
read_only_call_limit_write_length = 0
read_only_call_limit_read_length = 100000
read_only_call_limit_write_count = 0
read_only_call_limit_read_count = 30
read_only_call_limit_runtime = 1000000000
```
Start the [`stacks-blockchain`][] container with the following command:
```sh
docker run -d --rm \
--name stacks-blockchain \
-v $(pwd)/persistent-data/stacks-blockchain/mainnet:/root/stacks-node/data \
-v $(pwd)/config/mainnet:/src/stacks-node \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain \
/bin/stacks-node start --config /src/stacks-node/Config.toml
```
You can verify the running [`stacks-blockchain`][] container with the command:
```sh
docker ps --filter name=stacks-blockchain
```
## Step 3: verifying the services
-> The initial burnchain header sync can take several minutes, until this is done the following commands will not work
To verify the [`stacks-blockchain`][] burnchain header sync progress:
```sh
docker logs stacks-blockchain
```
The output should be similar to the following:
```
INFO [1626290705.886954] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.2% (8000 out of 691034)
INFO [1626290748.103291] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.4% (10000 out of 691034)
INFO [1626290776.956535] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.7% (12000 out of 691034)
```
To verify the [`stacks-blockchain`][] tip height is progressing use the following command:
```sh
curl -sL localhost:20443/v2/info | jq
```
If the instance is running you should recieve terminal output similar to the following:
```json
{
"peer_version": 402653184,
"pox_consensus": "89d752034e73ed10d3b97e6bcf3cff53367b4166",
"burn_block_height": 666143,
"stable_pox_consensus": "707f26d9d0d1b4c62881a093c99f9232bc74e744",
"stable_burn_block_height": 666136,
"server_version": "stacks-node 2.0.11.1.0-rc1 (master:67dccdf, release build, linux [x86_64])",
"network_id": 1,
"parent_network_id": 3652501241,
"stacks_tip_height": 61,
"stacks_tip": "e08b2fe3dce36fd6d015c2a839c8eb0885cbe29119c1e2a581f75bc5814bce6f",
"stacks_tip_consensus_hash": "ad9f4cb6155a5b4f5dcb719d0f6bee043038bc63",
"genesis_chainstate_hash": "74237aa39aa50a83de11a4f53e9d3bb7d43461d1de9873f402e5453ae60bc59b",
"unanchored_tip": "74d172df8f8934b468c5b0af2efdefe938e9848772d69bcaeffcfe1d6c6ef041",
"unanchored_seq": 0,
"exit_at_block_height": null
}
```
## Stopping the mainnet node
Use the following commands to stop the local mainnet node:
```sh
docker stop stacks-blockchain
```
## Optional. Run stacks node with own bitcoin node
It's encouraged to use your own bitcoin node when possible.
To do this simply update the `stacks-node/config/mainnet/Config.toml` file with the details of your bitcoin node. For example:
```
[burnchain]
chain = "bitcoin"
mode = "mainnet"
peer_host = "localhost"
username = "rpc username"
password = "rpc password"
rpc_port = 8332
peer_port = 8333
```
The rpc configuration of your bitcoin node is out of the scope of this document, but you can find more information on how to set it up [here](https://developer.bitcoin.org/examples/intro.html).
## Additional reading
- [Running an API instance with Docker][]
[Running an API instance with Docker]: https://docs.hiro.so/get-started/running-api-node
[`stacks-blockchain`]: https://github.com/stacks-network/stacks-blockchain

141
src/pages/es/understand-stacks/running-testnet-node.md

@ -0,0 +1,141 @@
---
title: Running a testnet node
description: Set up and run a testnet node with Docker
icon: TestnetIcon
duration: 15 minutes
experience: beginners
tags:
- tutorial
images:
large: /images/cli.svg
sm: /images/cli.svg
---
## Introduction
This procedure demonstrates how to run a local testnet node using Docker images.
-> This procedure focuses on Unix-like operating systems (Linux and MacOS). This procedure has not been tested on Windows.
## Prerequisites
Running a node has no specialized hardware requirements. Users have been successful in running nodes on Raspberry Pi boards and other system-on-chip architectures. In order to complete this procedure, you must have the following software installed on the node host machine:
- [Docker](https://docs.docker.com/get-docker/)
- [curl](https://curl.se/download.html)
- [jq](https://stedolan.github.io/jq/download/)
### Firewall configuration
In order for the API node services to work correctly, you must configure any network firewall rules to allow traffic on the ports discussed in this section. The details of network and firewall configuration are highly specific to your machine and network, so a detailed example isn't provided.
The following ports must open on the host machine:
Ingress:
- stacks-blockchain (open to `0.0.0.0/0`):
- `20443 TCP`
- `20444 TCP`
Egress:
- `18332`
- `18333`
- `20443-20444`
These egress ports are for syncing [`stacks-blockchain`][] and Bitcoin headers. If they're not open, the sync will fail.
## Step 1: initial setup
In order to run the testnet node, you must download the Docker images and create a directory structure to hold the persistent data from the services. Download and configure the Docker images with the following commands:
```sh
docker pull blockstack/stacks-blockchain
```
Create a directory structure for the service data with the following command:
```sh
mkdir -p ./stacks-node/persistent-data/stacks-blockchain/testnet && cd stacks-node
```
## Step 2: running Stacks blockchain
Start the [`stacks-blockchain`][] container with the following command:
```sh
docker run -d --rm \
--name stacks-blockchain \
-v $(pwd)/persistent-data/stacks-blockchain/testnet:/root/stacks-node/data \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain \
/bin/stacks-node xenon
```
You can verify the running [`stacks-blockchain`][] container with the command:
```sh
docker ps --filter name=stacks-blockchain
```
## Step 3: verifying the services
-> The initial burnchain header sync can take several minutes, until this is done the following commands will not work
To verify the [`stacks-blockchain`][] burnchain header sync progress:
```sh
docker logs stacks-blockchain
```
The output should be similar to the following:
```
INFO [1626290705.886954] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.2% (8000 out of 2034380)
INFO [1626290748.103291] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.4% (10000 out of 2034380)
INFO [1626290776.956535] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.7% (12000 out of 2034380)
```
To verify the [`stacks-blockchain`][] tip height is progressing use the following command:
```sh
curl -sL localhost:20443/v2/info | jq
```
If the instance is running you should recieve terminal output similar to the following:
```json
{
"peer_version": 4207599105,
"pox_consensus": "12f7fa85e5099755a00b7eaecded1aa27af61748",
"burn_block_height": 2034380,
"stable_pox_consensus": "5cc4e0403ff6a1a4bd17dae9600c7c13d0b10bdf",
"stable_burn_block_height": 2034373,
"server_version": "stacks-node 2.0.11.2.0-rc1 (develop:7b6d3ee+, release build, linux [x86_64])",
"network_id": 2147483648,
"parent_network_id": 118034699,
"stacks_tip_height": 509,
"stacks_tip": "e0ee952e9891709d196080ca638ad07e6146d4c362e6afe4bb46f42d5fe584e8",
"stacks_tip_consensus_hash": "12f7fa85e5099755a00b7eaecded1aa27af61748",
"genesis_chainstate_hash": "74237aa39aa50a83de11a4f53e9d3bb7d43461d1de9873f402e5453ae60bc59b",
"unanchored_tip": "32bc86590f11504f17904ee7f5cb05bcf71a68a35f0bb3bc2d31aca726090842",
"unanchored_seq": 0,
"exit_at_block_height": null
}
```
## Stopping the testnet node
Use the following commands to stop the local testnet node:
```sh
docker stop stacks-blockchain
```
## Additional reading
- [Running an API instance with Docker][]
[Running an API instance with Docker]: https://docs.hiro.so/get-started/running-api-node
[`stacks-blockchain`]: https://github.com/stacks-network/stacks-blockchain

131
src/pages/es/understand-stacks/stacking.md

@ -0,0 +1,131 @@
---
title: Stacking
description: Introduction to the reward mechanism of Proof-of-Transfer
images:
sm: /images/pages/stacking-rounded.svg
---
## Introduction
Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time.
Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks 2.0 network.
-> The Stacking consensus algorithm is implemented as a smart contract, using [Clarity](/write-smart-contracts/overview). [Read more about the contract](#stacking-contract).
## Stacking flow
The Stacking mechanism can be presented as a flow of actions:
![Stacking flow](/images/stacking-illustration.png)
1. Make API calls to get details about the upcoming reward cycle
2. For a specific Stacks account, confirm eligibility
3. Confirm the BTC reward address and the lockup duration
4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase
5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address
6. During the lockup period, details about unlocking timing, rewards and more can be obtained
7. Once the lockup period is passed, the tokens are released and accessible again
8. Display reward history, including details like earnings for previous reward cycles
-> Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network.
If you would like to implement this flow in your own wallet, exchange, or any other application, please have a look at this tutorial:
[@page-reference | inline] | /understand-stacks/integrate-stacking
[@page-reference | inline] | /understand-stacks/stacking-using-CLI
## Stacking delegation flow
The Stacking flow is different for delegation use cases:
![Delegated tacking flow](/images/stacking-delegation-illustration.png)
- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator
- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack
- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking
- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle
- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6)
- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights
## PoX mining
PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol.
-> A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens
![Mining flow](/images/pox-mining-flow.png)
Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases:
- Registration: miners register for a future election by sending consensus data to the network
- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders
- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain
- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens
[@page-reference | inline] | /start-mining/mainnet, /start-mining/testnet
## Token holder eligibility
Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must:
- Commit to participation before a reward cycle begins
- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum
- Lock up STX tokens for a specified period
- Provide a supported Bitcoin address to receive rewards (native segwit is not supported)
The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club.
![Dynamic minimum for individual eligibility](/images/stacking-dynamic-minimum.png)
Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn).
## Stacking in the PoX consensus algorithm
Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm.
![PoX cycles](/images/pox-cycles.png)
- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards
- A reward cycle consists of two phases: prepare and reward
- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle
- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set
- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip
- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned
- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes
## Stacking contract
Check out the [Stacking contract reference](/references/stacking-contract) to see available methods and error codes.
## Bitcoin address
!> You must provide a BTC address in one of two formats: [Legacy (P2PKH)](https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash), which starts with `1`. Or, [Segregated Witness / Segwit (P2SH)](https://en.bitcoin.it/wiki/Pay_to_script_hash), which starts with `3`. The "Native Segwit" format (which starts with "bc1"), for example, is not supported.
The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address.
The address must be specified in the following format using the Clarity language:
```clar
;; a tuple of a version and hashbytes buffer
(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20))))
```
The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following:
```js
SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh
SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh
SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh
SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh
```
The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib):
```js
const btc = require('bitcoinjs-lib');
console.log(
'0x' + btc.address.fromBase58Check('1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6').hash.toString('hex')
);
```

46
src/pages/es/understand-stacks/stacks-blockchain-api.md

@ -0,0 +1,46 @@
---
title: Stacks Blockchain API
description: Interacting with the Stacks 2.0 Blockchain via API
images:
sm: /images/pages/testnet-sm.svg
---
## Introduction
The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain.
~> The RESTful API is developed by Hiro. Hiro also hosts a public API node for easy onboarding. Using it requires you to trust the hosted server, but provides a faster onboarding experience. You can [run your own API server](https://docs.hiro.so/get-started/running-api-node)
The RESTful JSON API can be used without any authorization. The basepath for the API is:
```bash
# for mainnet, replace `testnet` with `mainnet`
https://stacks-node-api.testnet.stacks.co/
```
-> This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api).
### Stacks Node RPC API
The [stacks-node implementation](https://github.com/stacks-network/stacks-blockchain/) exposes JSON RPC endpoints.
All `/v2/` routes a proxied to a Hiro-hosted Stacks Node. For a trustless architecture, you should make these requests to a self-hosted node.
## Proxied Stacks Node RPC API endpoints
The Stacks 2.0 Blockchain API is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node.
-> The Stacks Blockchain API proxies to Node RPC endpoints
While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints:
- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions)
- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface)
- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry)
- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source)
- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info)
- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function)
- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer)
- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info)
~> If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`.

72
src/pages/es/understand-stacks/technical-specs.md

@ -0,0 +1,72 @@
---
title: Technical Specifications
description: Summary of technical specifications of Stacks 2.0
---
## Consensus
- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md)
- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md).
- Threat model
- 51% of malicious Stacks mining power can perform a double-spend attack
- 51% of malicious Bitcoin mining power can reorg the Stacks chain
- Different actors and their roles
- Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream.
- Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle.
- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations.
- For more details, see [Proof of Transfer](/understand-stacks/proof-of-transfer).
## Proof of Transfer Mining
- Coinbase reward schedule:
- 1000 STX/block for first 4 years
- 500 STX/block for following 4 years
- 250 STX/block for subsequent 4 years
- 125 STX/block in perpetuity after that
- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high.
- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks.
- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine.
- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes.
- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust."
- For more details, see [Mining](/understand-stacks/mining).
## Stacking
- Stacking works in 2 phases
1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts
2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks).
- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block.
- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX.
- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation).
- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx).
- Only two types of BTC reward addresses are supported: [Legacy (P2PKH)](https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash) or [Segregated Witness / Segwit (P2SH)](https://en.bitcoin.it/wiki/Pay_to_script_hash). Native Segwit is not supported.
- Further reading: [Stacking](/stacks-blockchain/stacking)
## Accounts and Addresses
- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts
- An account is fully specified by its address + nonce + assets
- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes)
- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above)
- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value.
- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account.
- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use.
- Further reading: [Accounts](/understand-stacks/accounts)
## Transactions
- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock.
- Only standard accounts (not contracts) can pay transaction fees.
- Transaction execution is governed by 3 accounts (may or may not be distinct)
1. _originating account_ is the account that creates, _authorizes_ and sends the transaction
2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction
3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function
- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](/understand-stacks/microblocks)), a faster confirmation time is possible.
- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts.
- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account.
- Mempool limit for concurrent pending transactions is 25 per account
- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours
- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding)
- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying)
- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete.
- Transactions can include a memo string (max 34 bytes)

27
src/pages/es/understand-stacks/testnet.md

@ -0,0 +1,27 @@
---
title: Testnet
description: Test your smart contracts and apps
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## About testnet
The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset.
## Testnet API
The hosted [Stacks Blockchain API](/understand-stacks/stacks-blockchain-api) for the testnet is available at this base URL:
```shell
https://stacks-node-api.testnet.stacks.co/
```
### Faucet
The testnet faucet provides you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. You can get STX from the faucet on the [Stacks Explorer Sandbox](https://explorer.stacks.co/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets).
To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab and click "Request STX" button. If you would like to get enough STX tokens to try out [Stacking](/understand-stacks/stacking), and click "I want to stack."
> The Explorer Sandbox requires you to login with a Secret Key

43
src/pages/es/understand-stacks/transactions.md

@ -0,0 +1,43 @@
---
title: Transactions
description: Guide to Stacks 2.0 transactions
icon: TestnetIcon
images:
large: /images/transaction-signing.svg
sm: /images/transaction-signing.svg
---
## Introduction
Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](/understand-stacks/accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions.
## Lifecycle
Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network.
![Transaction lifecycle](/images/tx-lifecycle.png)
- **Generate**: Transactions are assembled according to the encoding specification.
- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in.
- **Broadcast**: Transactions are sent to a node.
- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions.
- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made.
- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network.
-> A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`.
## Types
The Stacks 2.0 supports a set of different transaction types:
| **Type** | **Value** | **Description** |
| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. |
| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient |
| Contract deploy | `smart_contract` | Contract instantiation |
| Contract call | `contract_call` | Contract call for a public, non read-only function |
| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package |
A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id).
~> Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](/understand-stacks/network#read-only-function-calls).

58
src/pages/es/write-smart-contracts/overview.md

@ -0,0 +1,58 @@
---
title: Clarity overview
description: Overview and guides for getting started with Clarity
images:
large: /images/contract.svg
sm: /images/contract.svg
---
## Introduction
Clarity is a programming language for writing smart contracts on the Stacks 2.0 blockchain. It supports programmatic control over digital assets.
## Smart contracts
Smart contracts encode and enforce rules for modifying a particular set of data that is shared among people and entities who don't necessarily trust each other. For example, a smart contract can hold funds in escrow until multiple parties agree to release them, create its own ledger and keep track of its own novel tokens (fungible or non-fungible), and even help make supply chains more transparent.
Because smart contracts are programs that exist in a blockchain, anyone can query them, and anyone can submit transactions to execute them. A smart contract execution can result in new transactions being written to the blockchain.
Apps can take advantage of smart contracts to manage a global state that is visible to the public. Anyone can audit the blockchain to independently verify that an app's global shared state has been managed correctly according to the smart contract's rules.
There is a [Clarity Visual Studio Code plugin][] available for syntax assistance and debugging.
## Use cases
Not every decentralized application requires smart contracts, but Clarity unlocks interesting capabilities for decentralized applications. Examples of use cases include, but are not limited to:
- Access control (for example pay to access)
- Non-fungible (for example collectibles) and fungible tokens (for example stablecoins)
- Business model templates (for example subscriptions)
- App-specific blockchains
- Decentralized Autonomous Organizations
## Language design
Clarity differs from most other smart contract languages in two essential ways:
- The language is interpreted and broadcast on the blockchain as is (not compiled)
- The language is decidable (not Turing complete)
Using an interpreted language ensures that the executed code is human-readable and auditable. A decidable language like Clarity makes it possible to determine precisely which code is executed, for any function.
A Clarity smart contract consists of two parts, a data space and a set of functions. Only the associated smart contract may modify its corresponding data space on the blockchain. Functions may be private and thus callable only from within the smart contract, or public and thus callable from other contracts. Users call smart contracts' public functions by broadcasting a transaction on the blockchain which invokes the public function. Contracts can also call public functions from other smart contracts.
Note some of the key Clarity language rules and limitations.
- The only primitive types are booleans, integers, buffers, and principals.
- Recursion is illegal and there are no anonymous functions.
- Looping is only performed via `map`, `filter`, or `fold`.
- There is support for lists, however, the only variable length lists in the language appear as function inputs; there is no support for list operations like append or join.
- Variables are immutable.
## Explore more
For language details and references, see the following:
[@page-reference | grid] | /write-smart-contracts/principals, /write-smart-contracts/values, /references/language-overview
[Clarity Visual Studio Code plugin]: https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp

238
src/pages/es/write-smart-contracts/principals.md

@ -0,0 +1,238 @@
---
title: Principals
description: 'Clarity: Understanding Principals'
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Introduction
_Principals_ are a Clarity native type that represents an entity that can have a token balance. This section discusses principals and how they are used in the Clarity.
## Principals and tx-sender
Assets in the smart contracting language and blockchain are "owned" by objects of the principal type, meaning that any object of the principal type may own an asset. For the case of public-key hash and multi-signature Stacks addresses, a given principal can operate on their assets by issuing a signed transaction on the blockchain. _Smart contracts_ may also be principals (represented by the smart contract's identifier), however, there is no private key associated with the smart contract, and it cannot broadcast a signed transaction on the blockchain.
A Clarity contract can use a globally defined `tx-sender` variable to obtain the current principal. The following example defines a transaction type that transfers `amount` microSTX from the sender to a recipient if amount is a multiple of 10, otherwise returning a 400 error code.
```clarity
(define-public (transfer-to-recipient! (recipient principal) (amount uint))
(if (is-eq (mod amount 10) 0)
(stx-transfer? amount tx-sender recipient)
(err u400)))
```
Clarity provides an additional variable to help smart contracts authenticate a transaction sender. The keyword `contract-caller` returns the principal that _called_ the current contract. If an inter-contract call occurred, `contract-caller` returns the last contract in the stack of callers. For example, suppose there are three contracts A, B, and C, each with an `invoke` function such that `A::invoke` calls `B::invoke` and `B::invoke` calls `C::invoke`.
When a user Bob issues a transaction that calls `A::invoke`, the value of `contract-caller` in each successive invoke function's body would change:
```clarity
in A::invoke, contract-caller = Bob
in B::invoke, contract-caller = A
in C::invoke, contract-caller = B
```
This allows contracts to make assertions and perform authorization checks using not only the `tx-sender` (which in this example, would always be "Bob"), but also using the `contract-caller`. This could be used to ensure that a particular function is only ever called directly and never called via an inter-contract call (by asserting that `tx-sender` and `contract-caller` are equal). We provide an example of a two different types of authorization checks in the rocket ship example below.
## Smart contracts as principals
Smart contracts themselves are principals and are represented by the smart contract's identifier -- which is the publishing address of the contract _and_ the contract's name, for example:
```clarity
'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR.contract-name
```
For convenience, smart contracts may write a contract's identifier in the form `.contract-name`. This will be expanded by the Clarity interpreter into a fully qualified contract identifier that corresponds to the same publishing address as the contract it appears in. For example, if the same publisher address, `SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR`, is publishing two contracts, `contract-A` and `contract-B`, the fully qualified identifier for the contracts would be:
```clarity
'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR.contract-A
'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR.contract-B
```
But, in the contract source code, if the developer wishes to call a function from `contract-A` in `contract-B`, they can write
```clarity
(contract-call? .contract-A public-function-foo)
```
This allows the smart contract developer to modularize their applications across multiple smart contracts _without_ knowing the publishing key a priori.
In order for a smart contract to operate on assets it owns, smart contracts may use the special `(as-contract ...)` function. This function executes the expression (passed as an argument) with the `tx-sender` set to the contract's principal, rather than the current sender. The `as-contract` function returns the value of the provided expression.
For example, a smart contract that implements something like a "token faucet" could be implemented as so:
```clarity
(define-map claimed-before
((sender principal))
((claimed bool)))
(define-constant err-already-claimed u1)
(define-constant err-faucet-empty u2)
(define-constant stx-amount u1)
(define-public (claim-from-faucet)
(let ((requester tx-sender)) ;; set a local variable requester = tx-sender
(asserts! (is-none (map-get? claimed-before {sender: requester})) (err err-already-claimed))
(unwrap! (as-contract (stx-transfer? stx-amount tx-sender requester)) (err err-faucet-empty))
(map-set claimed-before {sender: requester} {claimed: true})
(ok stx-amount)))
```
In this example, the public function `claim-from-faucet`:
- Checks if the sender has claimed from the faucet before.
- Assigns the tx sender to a `requester` variable.
- Adds an entry to the tracking map.
- Uses `as-contract` to send 1 microstack
Unlike other principals, there is no private key associated with a smart contract. As it lacks a private key, a Clarity smart contract cannot broadcast a signed transaction on the blockchain.
## Example: Authorization checks
The interactions between `tx-sender`, `contract-caller` and `as-contract` are subtle, but are important when performing authorization checks in a contract. In this example contract, we'll show two different kinds of authorization checks a contract may wish to perform, and then walk through how different ways in which contract functions may be called will pass or fail those checks.
This contract defines a "rocket-ship" non-fungible-token that a principal may own and manage the authorized pilots. Pilots are principals that are allowed to "fly" the rocket ship.
This contract performs two different authorization checks:
1. Before a ship is allowed to fly, the contract checks whether or not the transaction was created and signed by an authorized pilot. A pilot could, for example, call another contract, which then calls the `fly-ship` public function on the pilot's behalf.
2. Before modifying the allowed-pilots for a given rocket ship, the contract checks that the transaction was signed by the owner of the rocket ship. Furthermore, the contract requires that this function be called _directly_ by the ship's owner, rather than through a inter-contract-call.
The second type of check is more restrictive than the first check, and is helpful for guarding very sensitive routines --- it protects users from unknowingly calling a function on a malicious contract that subsequently tries to call sensitive functions on another contract.
```clarity
;;
;; rockets-base.clar
;;
(define-non-fungible-token rocket-ship uint)
;; a map from rocket ships to their allowed
;; pilots
(define-map allowed-pilots
((rocket-ship uint)) ((pilots (list 10 principal))))
;; implementing a contains function via fold
(define-private (contains-check
(y principal)
(to-check { p: principal, result: bool }))
(if (get result to-check)
to-check
{ p: (get p to-check),
result: (is-eq (get p to-check) y) }))
(define-private (contains (x principal) (find-in (list 10 principal)))
(get result (fold contains-check find-in
{ p: x, result: false })))
(define-read-only (is-my-ship (ship uint))
(is-eq (some tx-sender) (nft-get-owner? rocket-ship ship)))
;; this function will print a message
;; (and emit an event) if the tx-sender was
;; an authorized flyer.
;;
;; here we use tx-sender, because we want
;; to allow the user to let other contracts
;; fly the ship on behalf of users
(define-public (fly-ship (ship uint))
(let ((pilots (default-to
(list)
(get pilots (map-get? allowed-pilots { rocket-ship: ship })))))
(if (contains tx-sender pilots)
(begin (print "Flew the rocket-ship!")
(ok true))
(begin (print "Tried to fly without permission!")
(ok false)))))
;;
;; Authorize a new pilot.
;;
;; here we want to ensure that this function
;; was called _directly_ by the user by
;; checking that tx-sender and contract-caller are equal.
;; if any other contract is in the call stack, contract-caller
;; would be updated to a different principal.
;;
(define-public (authorize-pilot (ship uint) (pilot principal))
(begin
;; sender must equal caller: an intermediate contract is
;; not issuing this call.
(asserts! (is-eq tx-sender contract-caller) (err u1))
;; sender must own the rocket ship
(asserts! (is-eq (some tx-sender)
(nft-get-owner? rocket-ship ship)) (err u2))
(let ((prev-pilots (default-to
(list)
(get pilots (map-get? allowed-pilots { rocket-ship: ship })))))
;; don't add a pilot already in the list
(asserts! (not (contains pilot prev-pilots)) (err u3))
;; append to the list, and check that it is less than
;; the allowed maximum
(match (as-max-len? (append prev-pilots pilot) u10)
next-pilots
(ok (map-set allowed-pilots {rocket-ship: ship} {pilots: next-pilots}))
;; too many pilots already
(err u4)))))
```
### Extending functionality: Multi-flyer contract
The authorization scheme for `fly-ship` allows pilots to fly rocket-ships from other contracts. This allows other contracts to provide new functionality built around calling that function.
For example, we can create a contract that calls `fly-ship` for multiple rocket-ships in a single transaction:
```clarity
;;
;; rockets-multi.clar
;;
(define-private (call-fly (ship uint))
(unwrap! (contract-call? .rockets-base fly-ship ship) false))
;; try to fly all the ships, returning a list of whether
;; or not we were able to fly the supplied ships
(define-public (fly-all (ships (list 10 uint)))
(ok (map call-fly ships)))
```
### Authorization for Contract-Owned Assets
The check in `authorize-pilot` protects users from malicious contracts, but how would such a scheme support contract-owned assets? This is what the `as-contract` function is used for. The `as-contract` function executes the supplied closure as if the sender of the transaction was the current contract, rather than the user -- it does this by updating `tx-sender` to the current contract principal. We can use this to, for example, create a smart contract rocket-ship-line:
```clarity
;;
;; rockets-ship-line.clar
;;
(define-constant line-ceo 'SP19Y6GRV9X778VFS1V8WT2H502WFK33XZXADJWZ)
(define-data-var employed-pilots (list 10 principal) (list))
;; This function will:
;; * check that it is called by the line-ceo
;; * check that the rocket is owned by the contract
;; * authorize each employed pilot to the ship
(define-public (add-managed-rocket (ship uint))
(begin
;; only the ceo may call this function
(asserts! (is-eq tx-sender contract-caller line-ceo) (err u1))
;; start executing as the contract
(as-contract (begin
;; make sure the contract owns the ship
(asserts! (contract-call? .rockets-base is-my-ship ship) (err u2))
;; register all of our pilots on the ship
(add-pilots-to ship)))))
;; add all the pilots to a ship using fold --
;; the fold checks the return type of previous calls,
;; skipping subsequent contract-calls if one fails.
(define-private (add-pilot-via-fold (pilot principal) (prior-result (response uint uint)))
(let ((ship (try! prior-result)))
(try! (contract-call? .rockets-base authorize-pilot ship pilot))
(ok ship)))
(define-private (add-pilots-to (ship uint))
(fold add-pilot-via-fold (var-get employed-pilots) (ok ship)))
```
In order for the contract to add each pilot to a new ship, the contract must call `authorize-pilot`. However, the contract wants to perform this action on behalf of a ship the _contract_ owns, not the transaction sender. To do this, the contract uses `as-contract`.

72
src/pages/es/write-smart-contracts/tokens.md

@ -0,0 +1,72 @@
---
title: Tokens
description: Learn about token support within Clarity
icon: TestnetIcon
images:
large: /images/pages/nft/token.png
sm: /images/pages/nft/token.png
---
## Introduction
A fundamental use of blockchain technology is the representation, store, and transfer of value between users of a blockchain. Cryptocurrency is a very common use of blockchain technology, and remains one of the primary drivers of adoption of blockchain technology. Cryptocurrencies are represented by blockchain tokens: individual units of value within a given blockchain ecosystem. Blockchain tokens can extend beyond just digital currency, however, and recent developments throughout the cryptocurrency community have demonstrated potential for the use of blockchain to tokenize and represent not just money but other tangible assets.
A blockchain token is a digital asset that can be verifiably owned by a user of a blockchain. Blockchain tokens are governed by a set of rules that are defined by either the blockchain itself (in the case of native tokens) or by a smart contract on a blockchain. Rules can vary depending on the nature and the use of the token.
Tokens on a blockchain fall into two general categories, depending on their properties: [fungible][] or [non-fungible][]. The following sections discuss the properties of both types of tokens, and provide information about implementation of the two types of tokens on Stacks.
## Fungible tokens
A core property of any token on a blockchain is fungibility. A fungible token is a token that's mutually interchangable or capable of mutual substitution. In other words, one quantity or part of a fungible token can be replaced by an equal quantity or part of the same fungible token. Fungible tokens are often used to represent real-world fungible assets like currency. The STX token is an example of a fungible token. Other examples include stablecoins, tokens that represent voting rights in a DAO, or tokens that algorithmically track the price of stocks.
Fungible tokens form one of the most important value propositions for blockchain technology, the ability to store value and exchange that value through both internal and external transactions. Because fungible tokens can be divided into smaller parts and recombined into the same value representation, they serve a great utility for transferring value between blockchain users.
The primary fungible token on the Stacks blockchain is the native token, STX. Because the Stacks blockchain allows for the creation of [smart contracts][], other fungible tokens can be created on the Stacks blockchain as well. [SIP-010][] specifies the standard for fungible tokens on the Stacks blockchain. This specification defines the functions and traits that a fungible token on Stacks _must_ have. By complying with this standard, fungible tokens on Stacks can be easily represented by wallets that support Stacks.
### Understanding the fungible token standard
The [SIP-010][] standard is an interface definition that allows Stacks applications and wallets to interact with fungible tokens in a standard way. Supporting the standard reduces complexity for token creators to get their tokens into the ecosystem. Under the [SIP-010][] standard, fungible tokens must have the following characteristics:
- Ability to transfer a specified amount of the token to a recipient (`transfer`). The recipient is required to be a Stacks principal.
- Ability to obtain the human-readable name of the token (`get-name`).
- Ability to obtain a short name (ticker symbol) for the token (`get-symbol`).
- Ability to get the number of decimals in the token representation (`get-decimals`). This is used to construct a representation of the token that humans would be familiar dealing with. For example, the US dollar has 2 decimals, if the base unit is cents.
- Ability to get the balance of the token for a particular Stacks principal (`get-balance-of`).
- Ability to get the total supply of the token (`get-total-supply`).
- A URI to metadata associated with the token (`get-token-uri`). This can resolve to off-chain metadata about the token or contract, such as an image icon for the token or a description.
### Examples of fungible tokens on Stacks
- [Nothing](https://nothingtoken.com/) ([contract](https://explorer.stacks.co/txid/0x022bed728d648ff1a68036c40f3aff8136ee22fee18380731df0ab9d76d3c4a9?chain=mainnet))
## Non-fungible tokens (NFTs)
Non-fungible tokens (NFTs) are a type of token that are not interchangeable. NFTs have unique traits (usually in the form of attached metadata) that restrict the abillity to replace them with identical tokens. An NFT is a token that is unique, such as a piece of art, or ownership rights to a real-world asset such as a house.
NFTs alone don't have an inherent value, like a currency. The value of an NFT is derived from the assets that the NFT represents. The use of NFTs are myriad, including digital art, collectibles, domain names, and representation of ownership of content rights. NFTs can be used as digital certificates that track the authenticty of real world items, or digitize the ownership rights to property.
As with fungible tokens, NFTs on the Stacks blockchain are created with [smart contracts][]. [SIP-009][] specifies the standard for NFTs on the Stacks blockchain. This specification defines the functions and traits that an NFT _must_ have, but most NFTs have more functions or traits attached than those solely described by the specification. By complying with this standard, non-fungible tokens on Stacks can be easily represented by wallets that support Stacks.
### Understanding the non-fungible token standard
The [SIP-009][] standard is an interface definition that the Stacks ecosystem aligned on. With support for this standard across wallets and tools, it becomes easy to interact with NFTs. Under the [SIP-009][] standard, NFT contract must have the following characteristics:
- Ability to obtain the last token identifier (`get-last-token-id`). This id represents the upper limit of NFTs issued by the contract.
- A URI to metadata associated with a specific token identifier. (`get-token-uri`). This URI could resolve to a JSON file with information about the creator, associated media files, descriptions, signatures, and more.
- Ability to verify the owner for a given token identifier (`get-owner`). The owner resolves to a [Stacks principal](/write-smart-contracts/principals).
- Ability to transfer an NFT to a recipient (`transfer`). The recipient is required to be a Stacks principal.
### Examples of NFTs on Stacks
- [This is #1](https://thisisnumberone.com) ([contract](https://explorer.stacks.co/txid/SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.thisisnumberone-v2?chain=mainnet))
## Further reading
- [The Difference Between Fungible and Non-Fungible Tokens](https://101blockchains.com/fungible-vs-non-fungible-tokens/)
- [Explain It Like I Am 5: NFTs](https://messari.io/article/explain-it-like-i-am-5-nfts)
[fungible]: #fungible-tokens
[non-fungible]: #non-fungible-tokens-nfts
[smart contracts]: /write-smart-contracts/overview
[SIP-010]: https://github.com/hstove/sips/blob/feat/sip-10-ft/sips/sip-010/sip-010-fungible-token-standard.md
[SIP-009]: https://github.com/friedger/sips/blob/main/sips/sips/sip-009-nft-standard.md

305
src/pages/es/write-smart-contracts/values.md

@ -0,0 +1,305 @@
---
title: Clarity Values
description: Learn how to deal with Clarity Values in JavaScript
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Introduction
The Clarity language makes use of a strong static [type system](/references/language-clarity#clarity-type-system). This simply means that every function defined in Clarity expects arguments of specific types, and that a failure to provide properly typed arguments will result in your code failing to compile, or your contract call transactions failing prior to execution.
In order to build web applications that interact with Clarity contracts, you will need to learn how to construct and use `ClarityValue` objects. The [@stacks/transactions](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library makes this easy, as we will demonstrate below.
## Clarity Types
Please see the following page for information on Clarity Types:
[@page-reference | inline] | /references/language-types
## Constructing Clarity Values and accessing their data
Clarity values can be constructed with functions provided by the [@stacks/transactions](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library. These functions simply output javascript objects that contain a value and a numerical representation of the Clarity type information. The Clarity types are encoded as follows:
```typescript
export enum ClarityType {
Int = 0,
UInt = 1,
Buffer = 2,
BoolTrue = 3,
BoolFalse = 4,
PrincipalStandard = 5,
PrincipalContract = 6,
ResponseOk = 7,
ResponseErr = 8,
OptionalNone = 9,
OptionalSome = 10,
List = 11,
Tuple = 12,
StringASCII = 13,
StringUTF8 = 14,
}
```
`ClarityValue` objects can be serialized and included in transactions that interact with published Clarity contracts.
Here are examples of how to construct each type of Clarity value, and how to access its data if it has any:
### Booleans
```typescript
const t = trueCV();
// { type: ClarityType.BoolTrue }
const f = falseCV();
// { type: ClarityType.BoolFalse }
```
Boolean Clarity Values don't contain any underlying data. They are simply objects with `type` information.
### Optional Values
```typescript
const nothing: NoneCV = noneCV();
// { type: ClarityType.OptionalNone }
const something: SomeCV = someCV(trueCV());
// { type: ClarityType.OptionalSome, value: { type: 4 } }
```
Optional Clarity Values can either be nothing (an empty type that has no data), or something (a wrapped value).
If you are dealing with a function or contract function that returns an `OptionalCV`, you should always check what type it is before trying to access its value.
```typescript
const maybeVal: OptionalCV = await callReadOnlyFunction(...);
if (maybeVal.type === ClarityType.OptionalSome) {
console.log(maybeVal.value);
} else if (maybeVal.type === ClarityType.OptionalNone) {
// deal with `none` value
}
```
### Buffers
```typescript
const buffer = Buffer.from('foo');
const bufCV: BufferCV = bufferCV(buffer);
// { type: ClarityType.Buffer, buffer: <Buffer 66 6f 6f> }
```
### Integers
Clarity supports both integers and unsigned integers.
```typescript
const i: IntCV = intCV(-10);
// { type: ClarityType.Int, value: BN { ... } }
const u: UIntCV = uintCV(10);
// { type: ClarityType.UInt, value: BN { ... } }
```
Clarity value ints store their underlying data as `BigNum` values from the [bn.js](https://github.com/indutny/bn.js/) library.
In order to display/print Clarity (u)int values, use the `cvToString(val)` method.
If you wish to perform arithmetic operations using Clarity (u)int values, you must use methods from the `BigNum` api on their underlying `BigNum` values, and the construct a new Clarity value out of the result. For example:
```typescript
const x = intCV(1);
const y = intCV(2);
x.value.add(y.value);
// 3
```
### Strings
```typescript
const ascii: StringAsciiCV = stringAsciiCV('hello world');
// { type: ClarityType.StringASCII, data: 'hello world' }
const utf8: StringUtf8CV = stringUtf8CV('hello 🌾');
// { type: ClarityType.StringUTF8, data: 'hello 🌾' }
```
Clarity supports both ascii and utf8 strings.
### Principals
```typescript
const address = 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B';
const contractName = 'contract-name';
const spCV = standardPrincipalCV(address);
// {
// type: ClarityType.PrincipalStandard
// address: {
// type: StacksMessageType.Address,
// version: AddressVersion.MainnetSingleSig,
// hash160: "SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B"
// }
// }
const cpCV = contractPrincipalCV(address, contractName);
// {
// type: ClarityType.PrincipalContract,
// contractName: {
// type: StacksMessageType.LengthPrefixedString,
// content: 'contract-name',
// lengthPrefixBytes: 1,
// maxLengthBytes: 128,
// },
// address: {
// type: StacksMessageType.Address,
// version: AddressVersion.MainnetSingleSig,
// hash160: "SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B"
// }
// }
```
Both kinds of Clarity principal values contain `type` information and an `address` object. Contract principals also contain a `contractName`.
### Response Values
```typescript
const errCV = responseErrorCV(trueCV());
// { type: ResponseErr, value: { type: ClarityType.BoolTrue } }
const okCV = responseOkCV(falseCV());
// { type: ResponseOk, value: { type: ClarityType.BoolFalse } }
```
Response Clarity Values will either have the type `ClarityType.ResponseOk` or `ClarityType.ResponseErr`. They both contain a Clarity Value. Often this value will be an integer error code if the response is an `Error`.
### Tuples
```typescript
const tupCV = tupleCV({
a: intCV(1),
b: trueCV(),
c: falseCV(),
});
// {
// type: ClarityType.Tuple,
// data: {
// a: { type: ClarityType.Int, value: BN { ... } },
// b: { type: ClarityType.BoolTrue },
// c: { type: ClarityType.BoolFalse },
// }
// }
console.log(tupCV.data['b']);
// { type: ClarityType.BoolTrue }
```
Tuples in Clarity are typed and contain named fields. The tuple above, for example, contains three fields with the names **a**, **b** and **c**, and the types of their values are `Int`, `Boolean` and `Boolean`, respectively.
Clarity tuples are represented in JavaScript as objects and a tuple's data can be accessed by its `data` field, where the underlying JS object is stored.
### Lists
```typescript
const l = listCV([trueCV(), falseCV()]);
// { type: ClarityType.List, list: [{ type: ClarityType.BoolTrue }] }
console.log(l.list[0]);
// { type: ClarityType.BoolTrue }
```
Lists, in Clarity, are homogeneous, meaning they can only contain elements of a singular (Clarity) type. Make sure to avoid constructing lists that have elements of multiple types.
A Clarity lists underlying data can be accessed via its `list` field.
## Using Clarity Values
Now that you know how to construct _and_ deconstruct Clarity values, you can use them to build `contract-call` transactions that call smart contract functions, and you can utilize their responses.
This is covered in depth [here](/understand-stacks/transactions#construction).
## Utilizing Clarity Values from Transaction Responses
`Read-only` Clarity functions can return Clarity values as a response. These `read-only` functions can be accessed easily in JavaScript via the [`callReadOnlyFunction()`](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#calling-read-only-contract-function) function included in `@stacks/transactions`, which returns a `ClarityValue`.
As mentioned above, `ClarityValues` are simply javascript objects containing a value and its associated Clarity type information. These object types are defined [here](https://github.com/hirosystems/stacks.js/tree/1f2b5fd8bdf1c2b5866e8171163594d7708a8c7a/packages/transactions/src/clarity/types).
When you are calling a `read-only` contract function, you will always know what type the function will return, since functions in Clarity are strongly typed.
It is common for Clarity functions to return values wrapped in a `Response`, in order to indicate if there was success or an error.
Since every `ClarityValue` has a `type` field, the type of the result of a `read-only` function call can be checked and acted upon like so:
```typescript
const contractAddress = 'ST3KC0MTNW34S1ZXD36JYKFD3JJMWA01M55DSJ4JE';
const contractName = 'kv-store';
const functionName = 'get-value';
const buffer = bufferCVFromString('foo');
const network = new StacksTestnet(); // for mainnet, use `StacksMainnet()`
const senderAddress = 'ST2F4BK4GZH6YFBNHYDDGN4T1RKBA7DA1BJZPJEJJ';
const options = {
contractAddress,
contractName,
functionName,
functionArgs: [buffer],
network,
senderAddress,
};
// make a read-only call to a contract function that
// returns a Response
const result: ResponseCV = await callReadOnlyFunction(options);
if (result.type === ClarityType.ResponseOk) {
console.log(cvToString(result.value));
} else if (result.type === ClarityType.ResponseErr) {
throw new Error(`kv-store contract error: ${result.value.data}`);
}
```
### ClarityValues to/from Hex
If you receive a response from a transaction in the form of a `hex` string, you can deserialize it into a Clarity value like so:
```javascript
import { hexToCV } from '@stacks/transactions';
let cv = hexToCV('hex_string');
```
Similarly, you can convert a Clarity value to `hex` string like so:
```javascript
import { cvToHex, trueCV } from '@stacks/transactions';
let trueHex = cvToHex(trueCV());
```
## Debugging Clarity Values
Sometimes you might receive a Clarity value that you were not expecting. Logging the value to your console won't always prove to be useful, unless you have memorized the Clarity value type enum values.
In order to figure out what kind of value you are dealing with, you can use the `cvToString()` function to convert the Clarity value to a more easily readable string.
For example, calling `cvToString()` on a large `tuple` might yield something like:
```
(tuple
(a -1)
(b u1)
(c 0x74657374)
(d true)
(e (some true))
(f none)
(g SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B)
(h SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B.test)
(i (ok true))
(j (err false))
(k (list true false))
(l (tuple (a true) (b false)))
(m "hello world")
(n u"hello \u{1234}"))`
```

24
src/pages/fr/404.md

@ -0,0 +1,24 @@
---
title: Page not found
description: The page you're looking for isn't here.
---
## Whoops
Looks like the page you are looking for isn't here.
-> Developer content has recently moved to [docs.hiro.so](https://docs.hiro.so/). For more information on the content move, see [this post](https://forum.stacks.org/t/the-evolution-of-the-stacks-documentation-and-a-new-hiro-docs-site/12343) on the Stacks forum. Check for your content at [docs.hiro.so](https://docs.hiro.so/) or ask in Discord if you believe you have reached this page in error.
Try out some of these popular pages:
## Understand Stacks
[@page-reference | grid] | /understand-stacks/overview, /understand-stacks/proof-of-transfer, /understand-stacks/testnet
## Write smart contracts
[@page-reference | grid] | /write-smart-contracts/overview
## Start mining
[@page-reference | grid] | /start-mining/mainnet, /start-mining/testnet

27
src/pages/fr/build-apps/overview.md

@ -0,0 +1,27 @@
---
title: Build apps with Stacks
description: Authenticate users, sign transactions and store data with the Stacks blockchain
images:
large: /images/pages/build-apps.svg
sm: /images/pages/build-apps-sm.svg
---
## Introduction
Apps built with the Stacks blockchain give users control over their digital identities, assets, and data.
Unlike most cloud-based apps, they are "decentralized" since they don't depend on any centralized platform, server, or database to function. Rather, they use the Stacks blockchain to authenticate users and facilitate read and write requests for them without any single point of failure or trust.
Stacks provides three main functions for building apps:
- **Authentication**: Register and sign users in with identities on the Stacks blockchain
- **Transaction signing**: Prompt users to sign and broadcast transactions to the Stacks blockchain
- **Data storage**: Save and retrieve data for users with [Gaia](/build-apps/references/gaia)
All three of these integrations can be used together to create powerful new user experiences that rival or exceed those of traditional apps—all while protecting your users' digital rights.
While integration is possible for any type of app, most of the resources available here are for web developers experienced with JavaScript. See [Hiro developer docs](https://docs.hiro.so) for more information on the available app development libraries for Stacks.
## References
[@page-reference | grid] | /build-apps/references/authentication, /build-apps/references/bns, /build-apps/references/gaia

65
src/pages/fr/build-apps/references/authentication.md

@ -0,0 +1,65 @@
---
title: Authentication
description: Register and sign in users with identities on the Stacks blockchain
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Introduction
This guide explains how authentication is performed on the Stacks blockchain.
Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite.
Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](/build-apps/references/bns) and vice versa.
## How it works
The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side.
An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token.
These tokens are are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings.
When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter:
`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...`
When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`.
The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`.
The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions:
1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub
2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage.
3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions.
Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain.
The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/build-apps/references/gaia).
## Key pairs
Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular.
The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed.
### Transit private key
The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response.
The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request.
### Identity address private key
The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator.
This private key signs the authentication response token for an app to indicate that the user approves sign in to that app.
### App private key
The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input.
The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key.

244
src/pages/fr/build-apps/references/bns.md

@ -0,0 +1,244 @@
---
title: Blockchain Naming System
description: Binds Stacks usernames to off-chain state
images:
large: /images/nodes.svg
sm: /images/nodes.svg
---
Blockchain Naming System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control.
The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block.
Names in BNS have three properties:
- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state.
- **Names are human-meaningful.** Each name is chosen by its creator.
- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys.
The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network.
The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions.
## Motivation behind naming systems
We rely on naming systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's naming system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key.
What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be.
- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to.
- **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes.
- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states.
- **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene.
- In PGP, names are key IDs. They are are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference.
- **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system.
BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more:
- Build domain name services where hostnames can't be hijacked.
- Build social media platforms where user names can't be stolen by phishers.
- Build version control systems where repository branches do not conflict.
- Build public-key infrastructure where it's easy for users to discover and remember each other's keys.
## Organization of BNS
BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming:
- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators.
- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already.
- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules.
A feature comparison matrix summarizing the similarities and differences between these name objects is presented below:
| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** |
| -------------------------------------- | -------------- | ------------- | ------------------ |
| Globally unique | X | X | X |
| Human-meaningful | X | X | X |
| Owned by a private key | | X | X |
| Anyone can create | X | X | [1] |
| Owner can update | | X | [1] |
| State hosted on-chain | X | X | |
| State hosted off-chain | | X | X |
| Behavior controlled by consensus rules | X | X | |
| May have an expiration date | | X | |
[1] Requires the cooperation of a BNS name owner to broadcast its transactions
## Namespaces
Namespaces are the top-level naming objects in BNS.
They control a few properties about the names within them:
- How expensive they are to register
- How long they last before they have to be renewed
- Who (if anyone) receives the name registration fees
- Who is allowed to seed the namespace with its initial names.
At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered unspendable (the intention is to discourage ID squatters).
Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever.
However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`).
Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`.
## Subdomains
BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth.
BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations.
This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored.
For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file:
```bash
$TTL 3600
1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg=="
2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK"
10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo="
31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg=="
359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo="
30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg=="
onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg=="
10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo="
36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg=="
_http._tcp URI 10 1 "https://dotpodcast.co/"
```
Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to:
```json
{
"address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH",
"blockchain": "bitcoin",
"last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339",
"status": "registered_subdomain",
"zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3",
"zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n"
}
```
This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`.
### Subdomain Lifecycle
Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`.
The lifecycle of a subdomain and its operations is shown in Figure 2.
```
subdomain subdomain subdomain
creation update transfer
+----------------+ +----------------+ +----------------+
| cicero | | cicero | | cicero |
| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." |
| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ...
| seqn=0 | | seqn=1 | | seqn=2 |
| | | sig="xxxx" | | sig="xxxx" |
+----------------+ +----------------+ +----------------+
| | |
| off-chain | |
~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ...
| on-chain | |
V V (zone file hash ) V
+----------------+ +----------------+ +----------------+
| res_publica.id | | jude.id | | res_publica.id |
| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ...
+----------------+ +----------------+ +----------------+
blockchain blockchain blockchain
block block block
Figure 2: Subdomain lifetime with respect to on-chain name operations .A new
subdomain operation will only be accepted if it has a later "sequence=" number,
and a valid signature in "sig=" over the transaction body .The "sig=" field
includes both the public key and signature, and the public key must hash to
the previous subdomain operation's "addr=" field.
The subdomain-creation and subdomain-transfer transactions for
"cicero.res_publica.id" are broadcast by the owner of "res_publica.id."
However, any on-chain name ("jude.id" in this case) can broadcast a subdomain
update for "cicero.res_publica.id."
```
Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include:
- The next sequence number
- The public key that hashes to the previous subdomain transaction's address
- A signature from the corresponding private key over the entire subdomain operation.
If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored.
Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain.
### Subdomain Creation and Management
Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular:
- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`.
- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key.
- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files.
- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`.
That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner.
Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network.
If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it.
### Subdomain Registrars
Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin.
We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application.
# BNS and DID Standards
BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs).
Each name in BNS has an associated DID. The DID format for BNS is:
```bash
did:stack:v0:{address}-{index}
```
Where:
- `{address}` is an on-chain public key hash (for example a Bitcoin address).
- `{index}` refers to the `nth` name this address created.
For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`.
As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`).
The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not.
Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name:
- The name must exist
- The name's zone file hash must be the hash of a well-formed DNS zone file
- The DNS zone file must be present in the Stacks node's data.
- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token
- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name
Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do.
A RESTful API is under development.
## DID Encoding for Subdomains
Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take.
- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses).
- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively.
The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63).

92
src/pages/fr/build-apps/references/gaia.md

@ -0,0 +1,92 @@
---
title: Gaia
description: Decentralized storage architecture for off-chain data
images:
large: /images/pages/data-storage.svg
sm: /images/pages/data-storage-sm.svg
---
## Introduction
Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia.
Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage.
Storing data off of the blockchain ensures that Stacks applications can provide users with high performance and high availability for data reads and writes without introducing central trust parties.
## Understand Gaia in the Stacks architecture
The following diagram depicts the Stacks architecture and Gaia's place in it:
![Stacks Architecture](/images/architecture.png)
Blockchains require consensus among large numbers of people, so they can be slow. Additionally, a blockchain is not designed to hold a lot of data. This means using a blockchain for every bit of data a user might write and store is expensive. For example, imagine if an application were storing every tweet in the chain.
The Stacks blockchain addresses performance problems using a layered approach. The base layer consists of the Stacks blockchain and the Blockchain Naming System (BNS). The blockchain governs ownership of identities in the Stacks network. Identities can be names such as domain names, usernames, or application names.
When an identity is created, its creation is recorded in the Stacks blockchain. Identities make up the primary data stored into the Stacks blockchain. These identities correspond to routing data in the OSI stack. The routing data is stored in the Atlas Peer Network, the second layer. Every core node that joins the Stacks Network is able to obtain an entire copy of this routing data. Stacks uses the routing data to associate identities (domain names, user names, and application names) with a particular storage location in the final layer, the Gaia Storage System.
A Gaia Storage System consists of a _hub service_ and storage resource on a cloud software provider. The storage provider can be any commercial provider such as Azure, DigitalOcean, Amazon EC2, and so forth. Typically the compute resource and the storage resource reside same cloud vendor, though this is not a requirement. Gaia currently has driver support for S3, Azure Blob Storage, Google Cloud Platform and local disk, but the driver model allows for other backend support as well.
Gaia stores data as a simple key-value store. When an identity is created, a corresponding data store is associated with that identity on Gaia. When a user logs into a dApp, the authentication process gives the application the URL of a Gaia hub, which then writes to storage on behalf of that user.
The Stacks blockchain stores only identity data. Data created by the actions of an identity is stored in a Gaia Storage System. Each user has profile data. When a user interacts with a decentralized dApp that application stores application data on behalf of the user. Because Gaia stores user and application data off the blockchain, a Stacks DApp is typically more performant than DApps created on other blockchains.
## User control or how is Gaia decentralized?
A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider.
![Gaiastorage](/images/gaia-storage.png)
Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data.
The control of user data lies in the way that user data is accessed. When an application fetches a file `data.txt` for a given user `alice.id`, the lookup will follow these steps:
1. Fetch the `zonefile` for `alice.id`.
2. Read her profile URL from her `zonefile`.
3. Fetch Alice's profile.
4. _Verify_ that the profile is signed by `alice.id`'s key
5. Find the read-only url out of the profile's `appsMeta` section (e.g. `https://example-app.gaia.alice.org`).
6. Fetch the file from `https://example-app.gaia.alice.org/data.txt`.
Because `alice.id` has access to her [zonefile](https://docs.stacks.co/references/bns-contract#name-update), she can change where her profile is stored. For example, she may do this if the current profile's service provider or storage is compromised. To change where her profile is stored, she changes her Gaia hub URL to another Gaia hub URL. If a user has sufficient compute and storage resources, a user may run their own Gaia Storage System and bypass a commercial Gaia hub provider all together.
~> Users with existing identities cannot yet migrate their data from one hub to another.
Applications writing directly on behalf of `alice.id` do not need to perform a lookup. Instead, the [Stacks authentication flow](http://blockstack.github.io/stacks.js/index.html) provides Alice's chosen gaia hub URL to the application. This authentication flow _is also_ within Alice's control because Alice's wallet _must_ generate the authentication response.
## Understand data storage
A Gaia hub stores the written data _exactly_ as given. It offers minimal guarantees about the data. It does not ensure that data is validly formatted, contains valid signatures, or is encrypted. Rather, the design philosophy is that these concerns are client-side concerns.
Client libraries (such as [`Stacks.js`](https://stacks.js.org/)) are capable of providing these guarantees. A liberal definition of the [end-to-end principle](https://en.wikipedia.org/wiki/End-to-end_principle) guides this design decision.
When an application writes to a Gaia hub, an authentication token, key, and the data are passed to the Gaia hub.
![Gaia writes](/images/gaia-writes.png)
The token ensures the app has the authorization to write to the hub on the user's behalf.
## Gaia versus other storage systems
Here's how Gaia stacks up against other decentralized storage systems. Features that are common to all storage systems are omitted for brevity.
| Features | [Gaia](https://github.com/stacks-network/gaia) | [Sia](https://sia.tech/) | [Storj](https://storj.io/) | [IPFS](https://ipfs.io/) | [DAT](https://datproject.org/) | [SSB](https://www.scuttlebutt.nz/) |
| ------------------------------------------ | ---------------------------------------------- | ------------------------ | -------------------------- | ------------------------ | ------------------------------ | ---------------------------------- |
| User controls where data is hosted | X | | | | | |
| Data can be viewed in a normal Web browser | X | | | X | | |
| Data is read/write | X | | | | X | X |
| Data can be deleted | X | | | | X | X |
| Data can be listed | X | X | X | | X | X |
| Deleted data space is reclaimed | X | X | X | X | | |
| Data lookups have predictable performance | X | | X | | | |
| Writes permission can be delegated | X | | | | | |
| Listing permission can be delegated | X | | | | | |
| Supports multiple backends natively | X | | X | | | |
| Data is globally addressable | X | X | X | X | X | |
| Needs a cryptocurrency to work | | X | X | | | |
| Data is content-addressed | | X | X | X | X | X |
## Deploy your GAIA hub
Steps to deploy your own GAIA hub can be found [here](https://github.com/stacks-network/gaia/blob/master/deploy/README.md)

268
src/pages/fr/contributing.md

@ -0,0 +1,268 @@
---
title: How to contribute
description: Learn how this site is built, and how you could contribute to it.
icon: BlockstackIcon
images:
large: /images/contribute.svg
sm: /images/contribute.svg
---
## Introduction
Welcome. Thank you for your interest in contributing and helping make these docs as good as they can be. This page will outline how this site is built, its general structure, getting it running locally, and some helpful tips for using all of its features.
## Next.js, MDX, Markdown
This docs site is built with [Next.js](https://github.com/vercel/next.js) and uses something called [MDX](https://mdxjs.com/). Next.js is a framework built on top of React, and MDX is a tool that enables writing React code (JSX) within standard Markdown files. In addition to being able to write JSX in Markdown, it allows the application to render out all of the Markdown content with React components. This means that we are able to do some pretty complex things while a contributor only has to know how to write Markdown.
-> **Don't know what Markdown is?** Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/) for learning it.
## Getting started
To get started you have two options:
1. using web IDE Gitpod in your browser.
2. working locally.
### Working in browser
The web IDE gitpod provides an environment to contibute directly from within your browser.
To get started, you only have to a github account and open the link [https://gitpod.io/#https://github.com/stacks-network/docs](https://gitpod.io/#https://github.com/stacks-network/docs) in your browser.
### Working Locally
When workin locally with the site, a few things are needed:
- Familiarity with `git`, GitHub, and the command line. [Read more here.](https://docs.github.com/en/github/getting-started-with-github/quickstart)
- [`node` + `npm`,](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) and [`yarn` installed](https://yarnpkg.com/getting-started/install) on your machine.
- Some kind of code editor, such as VSCode, Sublime, or WebStorm.
-> This project requires at least Node version 12
### Working with GitHub
All of the code for this site is open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). Before you start editing anything, you will need to fork the repo so that you can have your own copy of the code under your GitHub profile. On the [repository's page](https://github.com/stacks-network/docs), you should be able to see a button in the upper right of the screen that says "Fork." [You can read about Forking here.](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo)
This is a generalized workflow for contributing to these docs:
- Clone your fork to your local machine with this command `git clone git@github.com:<YOUR_USERNAME>/docs.git stacks_docs`
- Enter your project folder `cd stacks_docs`
- Create a branch `git checkout -b feat/my-feature-branch`.
- Run the command `yarn` to install all of the dependencies.
- Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`.
- Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`.
- Visit GitHub and make your pull request.
### Running the site locally
Once you have the project on your computer and the dependencies have been installed via the `yarn` command, you can run `yarn dev` and it should give you a message such as:
```bash
yarn dev
```
```bash
yarn run v1.22.17
$ yarn clean:build-files && next dev
$ rimraf .next && rimraf .cache
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
warn - You have enabled experimental feature(s).
warn - Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use them at your own risk.
info - Disabled SWC as replacement for Babel because of custom Babel configuration "babel.config.js" https://nextjs.org/docs/messages/swc-disabled
info - automatically enabled Fast Refresh for 1 custom loader
info - Using external babel configuration from /home/alejandro/stacks-network_docs/babel.config.js
event - compiled client and server successfully in 13.5s (680 modules)
```
The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000).
## Project structure
### Pages
If you are interested in only adding new documentation content to the site, the files that will be important to you are located within `./src/pages/*`:
```bash showLineNumbers highlight=11
stacks_docs/
.github/
lib/
node_modules/
public/
src/
_data/
_includes/
common/
components/
pages/
types/
```
The routing for this site is file based, meaning if you created a folder within `/pages` named `clarity` and a then file named `overview.md`, you would be able to navigate to `http://localhost:3000/clarity/overview` and you would see whatever content is in that markdown file.
### Frontmatter
Frontmatter is the top part of any markdown document that is written in a language called [YAML](https://yaml.org/). It looks like this:
```yaml
---
title: This is my page title
description: A short, concise sentence describing what is on this page
---
```
Frontmatter gives us the ability to define some things within a page that the site can use, such as a page title or page description. When adding any new page, please include a `title` and `description`.
-> **Did you know?** The term _Frontmatter_ comes from the section in a book at the beginning detailing things like: publisher’s name and address, copyright information, table of contents, etc.
### Dynamic sidebar
The sidebar navigation is generated in a partially dynamic way. The application searches through a list of paths and parses the markdown to get some information about the page, such as the title and headings contained within the page.
#### Adding a new route
If you are adding a new route, you have to add your route to a section contained within this file: `src/common/navigation.yaml`
```bash showLineNumbers highlight=11
sections:
- pages:
- path: /
- path: /understand-stacks
pages:
- path: /overview
- path: /testnet
- path: /proof-of-transfer
- path: /mining
- path: /accounts
- path: /transactions
- path: /network
- path: /stacking
- path: /command-line-interface
- path: /local-development
- path: /technical-specs
- path: /stacks-blockchain-api
sections:
- title: Tutorials
pages:
- path: /managing-accounts
- path: /sending-tokens
- path: /running-testnet-node
- path: /integrate-stacking
- path: /stacking-using-CLI
```
Adding a new route requires to add a new `path`.
The script will process that file and pull out the title from the frontmatter of the document.
### Non-standard pages
There are a few pages within these docs that are non-standard markdown pages. This means they are using some kind of external data as their source, such as the [Clarity Reference page](/references/language-overview), or the [Stacks CLI page](https://docs.hiro.so/references/stacks-cli). These pages are using a function of Next.js called [`getStaticProps`](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) which allows us to fetch external data at runtime and use it in some way within our pages.
## Tips and tricks
### Style checks
We use the [Google Developer documentation style guides](https://developers.google.com/style/) in this project. Make sure to install [vale](https://github.com/errata-ai/vale) and run the style checks before you create a PR:
```bash
yarn check:style
```
### Use Conventional Commits
We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please.
### Always use Markdown when possible
It's possible to write standard HTML when writing in Markdown, but that should be avoided at all costs. We use `remark` to processes all Markdown, giving us things like automatically opening all external links in new windows, and adding IDs to headers. When we write things in HTML, such as a link or image, we don't get the benefit of the remark plugins as consistently as we would if we stuck to standar Markdown.
### Code blocks
The site uses `react-prism-renderer` and `prismjs` to add syntax highlighting to all of our code. You can see a full list of [languages supported here](https://github.com/PrismJS/prism/tree/master/components). We have a custom language definition for `clarity`, our smart contracting language located here. To add a new language, see this file: [`components/codeblock/index.tsx`](#).
To write a code block, you need to wrap your code in ` ```language `, and end your code block with ` ``` `. Here is an example of ` ```clarity `.
```clarity
(define-data-var counter int 0)
(define-public (get-counter)
(ok (var-get counter)))
```
#### Line highlighting
You can pass some extra data to tell the component to highlight specific lines:
` ```clarity highlight=1,4-6,13-17,28-32 `
Which will render:
```clarity highlight=1,4-6,13-17,28-32
(define-constant sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)
(define-constant recipient 'SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G)
(define-fungible-token novel-token-19)
(begin (ft-mint? novel-token-19 u12 sender))
(begin (ft-transfer? novel-token-19 u2 sender recipient))
(define-non-fungible-token hello-nft uint)
(begin (nft-mint? hello-nft u1 sender))
(begin (nft-mint? hello-nft u2 sender))
(begin (nft-transfer? hello-nft u1 sender recipient))
(define-public (test-emit-event)
(begin
(print "Event. Hello world")
(ok u1)))
(begin (test-emit-event))
(define-public (test-event-types)
(begin
(unwrap-panic (ft-mint? novel-token-19 u3 recipient))
(unwrap-panic (nft-mint? hello-nft u2 recipient))
(unwrap-panic (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR))
(unwrap-panic (stx-burn? u20 tx-sender))
(ok u1)))
(define-map store ((key (buff 32))) ((value (buff 32))))
(define-public (get-value (key (buff 32)))
(begin
(match (map-get? store ((key key)))
entry (ok (get value entry))
(err 0))))
(define-public (set-value (key (buff 32)) (value (buff 32)))
(begin
(map-set store ((key key)) ((value value)))
(ok u1)))
```
### Alerts
We use another remark plugin to generate certain kinds of alerts inline in our documentation.
```md
> This is a standard blockquote (non-alert).
-> This will be a standard note style alert.
=> This will be a success style alert.
~> This will be a warning style alert
!> This will be a danger style alert
```
Which renders:
> This is a standard blockquote (non-alert).
-> This will be a standard note style alert.
=> This will be a success style alert.
~> This will be a warning style alert
!> This will be a danger style alert

18
src/pages/fr/index.md

@ -0,0 +1,18 @@
---
title: Stacks documentation
description: Learn about Stacks mining, the STX token, and the Clarity smart contract language
---
-> Content related to developer tools and app development has recently moved to [docs.hiro.so](https://docs.hiro.so/). For more information on the content move, see [this post](https://forum.stacks.org/t/the-evolution-of-the-stacks-documentation-and-a-new-hiro-docs-site/12343) on the Stacks forum.
## Understand Stacks
[@page-reference | grid] | /understand-stacks/overview, /understand-stacks/proof-of-transfer, /understand-stacks/testnet
## Write smart contracts
[@page-reference | grid] | /write-smart-contracts/overview, /write-smart-contracts/tokens
## Start mining
[@page-reference | grid] | /start-mining/mainnet, /start-mining/testnet

24
src/pages/fr/references/bns-contract.md

@ -0,0 +1,24 @@
---
title: BNS Contract
description: See a detailed list of all functions and error codes of the BNS contract.
---
export { convertBNSRefToMdx as getStaticProps } from '@common/data/bns-ref'; import { BNSErrorcodeReference, BNSFunctionReference } from '@components/bns-ref';
## Introduction
The [Blockchain Naming System (BNS)](/build-apps/references/bns) is implemented as a smart contract using Clarity.
Below is a list of public and read-only functions as well as error codes that can be returned by those methods.
## Public functions
<BNSFunctionReference {...props.mdx.publicFunctions} />
## Read-only functions
<BNSFunctionReference {...props.mdx.readonlyFunctions} />
## Error codes
<BNSErrorcodeReference {...props.mdx.errorCodes} />

51
src/pages/fr/references/deploy-tips.md

@ -0,0 +1,51 @@
---
title: Deploy tips
description: Learn some common methods for deploying your application.
---
## Introduction
Stacks applications are web applications that authenticate users with Stacks Auth and store data with Gaia. Both of these technologies can be accessed on the client side. As such, Stacks apps tend to be simple in design and operation, since in many cases, they don’t have to host anything besides the application’s assets.
## Where to deploy your application
Before users can interact with your application, you must deploy it on a server that is accessible over the internet. Deploying requires that you:
- Configure or customize the files in the `public` directory.
- Build your application site for deployment.
- Copy your generated application files to your production server.
If you first populated your application with the Stacks application generator, your application contains the starting blocks for configuring, building, and deploying your app. For example, the React template builds out a scaffolding with the following building blocks.
| File or Directory | Description |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| node_modules/react-scripts | A set of scripts for that helps you kick off React projects without configuring, so you do not have to set up your project by yourself. |
| package.json | Contains a scripts section that includes a reference to the react-scripts, which are a dependency. This script creates a build directory containing your files for deployment. |
| public/favicon.ico | An example shortcut icon. |
| public/index.html | An entry page for an application. |
| public/manifest.json | A JSON file that describes your web application to the browser. |
| cors | Contains example deployment files for cross-origin request configuration. |
If you use the generator to build JavasScript or Vue scaffolding, your project configuration files will be different.
Regardless of which scaffolding you use, you must customize and extend this basic scaffolding as needed by your application. For example, you may want to add more properties to the `manifest.json` file. Since every application is different, Stacks Auth cannot give you specific instructions on how to do this. The steps you take are specific to your application.
## Stacks Authentication and deployment
When your application authenticates users with Stacks, the Stacks Wallet at on URL requests a resource (the app manifest) from your DApp. A request for a resource outside of the origin (the Stacks Wallet) is called as a _cross-origin request_(CORs). Getting data in this manner can be risky, so you must configure your website security to allow interactions across origins.
You can think of CORS interactions as an apartment building with Security. For example, if you need to borrow a ladder, you could ask a neighbor in your building who has one. Security would likely not have a problem with this request (that is, same-origin, your building). If you needed a particular tool, however, and you ordered it delivered from an online hardware store (that is, cross-origin, another site), Security may request identification before allowing the delivery man into the apartment building. (Credit: Codecademy)
The way you configure CORs depends on which company you use to host your web application. The application generator adds a `cors` directory to your application scaffolding. This directory contains files for Netlify (`_headers` and `_redirects`) as well as one for Firebase (`firebase.json`). The configurations in the `cors` directory make your application's `manifest.json` file accessible to other applications (for example, to the Stacks Browser). If you are deploying to a service other than Netlify or Firebase, you must configure CORS on that service to include the following headers when serving `manifest.json`:
````html
Access-Control-Allow-Origin: * Access-Control-Allow-Headers: "X-Requested-With, Content-Type,
Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding" Access-Control-Allow-Methods:
"POST, GET, OPTIONS, DELETE, PUT"```
````
Consult the documentation for your hosting service to learn how to configure CORS on that service.
## Deployment and Radiks
If you are deploying a Stacks application that uses Radiks, your deployment includes a server and a database component. You must take this into account when deploying your application. You may want to choose a service such as Heroku or Digital Ocean if your app uses Radiks.

24
src/pages/fr/references/faqs.md

@ -0,0 +1,24 @@
---
title: FAQs
description: Find answers related to the Stacks ecosystem.
---
## General Information
Learn more about the user-owned internet on Bitcoin and the Stacks ecosystem on [stacks.co](https://stacks.co).
## Apps and Smart Contracts
Developers, get started building apps and contracts on the [developer page at stacks.co](https://www.stacks.co/developers).
## Stacks Network
Learn more about the network behind the user-owned internet on Bitcoin in the [Understand Stacks chapter](/understand-stacks/overview) in the docs.
## Stacks Token
Stacks fuel apps and smart contracts on Bitcoin. Learn more at [stackstoken.com](https://stackstoken.com/faq).
## Stacks Wallet
Download and find resources about the Stacks Wallet by Hiro at [hiro.so](https://www.hiro.so/wallet).

8
src/pages/fr/references/glossary.md

@ -0,0 +1,8 @@
---
title: Glossary
description: A comprehensive list of terms used within the ecosystem.
---
export { convertGlossaryToJson as getStaticProps } from '@common/data/glossary'; import { Glossary } from '@components/glossary';
<Glossary data={props.glossary} />

10
src/pages/fr/references/language-functions.md

@ -0,0 +1,10 @@
---
title: Functions
description: See a detailed list of all functions for the Clarity language.
---
export { convertClarityRefToMdx as getStaticProps } from '@common/data/clarity-ref'; import { ClarityFunctionReference } from '@components/clarity-ref';
## Function reference
<ClarityFunctionReference {...props.mdx.functions} />

10
src/pages/fr/references/language-keywords.md

@ -0,0 +1,10 @@
---
title: Keywords
description: See a detailed list of all keywords for the Clarity language.
---
export { convertClarityRefToMdx as getStaticProps } from '@common/data/clarity-ref'; import { ClarityKeywordReference } from '@components/clarity-ref';
## Keyword reference
<ClarityKeywordReference {...props.mdx.keywords} />

84
src/pages/fr/references/language-overview.md

@ -0,0 +1,84 @@
---
title: Overview
description: Overview of the Clarity language constructs
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
export { convertClarityRefToMdx as getStaticProps } from '@common/data/clarity-ref'; import { ClarityKeywordReference, ClarityFunctionReference } from '@components/clarity-ref';
## Clarity Type System
The Clarity language uses a strong static type system. Function arguments and database schemas require specified types, and use of types is checked during contract launch. The type system does _not_ have a universal super type.
## Public Functions
Functions specified via `define-public` statements are _public_ functions and these are the only types of functions which may be called directly through signed blockchain transactions. In addition to being callable directly from a transaction (see the Stacks wire formats for more details on Stacks transactions), public function may be called by other smart contracts.
Public functions _must_ return a `(response ...)` type. This is used by Clarity to determine whether or not to materialize any changes from the execution of the function. If a function returns an `(err ...)` type, and mutations on the blockchain state from executing the function (and any function that it called during execution) will be aborted.
In addition to function defined via `define-public`, contracts may expose read-only functions. These functions, defined via `define-read-only`, are callable by other smart contracts, and may be queryable via public blockchain explorers. These functions _may not_ mutate any blockchain state. Unlike normal public functions, read-only functions may return any type.
## Contract Calls
A smart contract may call functions from other smart contracts using a `(contract-call?)` function.
This function returns a response type result-- the return value of the called smart contract function.
We distinguish 2 different types of `contract-call?`:
### Static dispatch
The callee is a known, invariant contract available on-chain when the caller contract is deployed. In this case, the callee's principal is provided as the first argument, followed by the name of the method and its arguments:
```clarity
(contract-call?
.registrar
register-name
name-to-register)
```
### Dynamic dispatch
The callee is passed as an argument, and typed as a trait reference (`<A>`).
```clarity
(define-public (swap (token-a <can-transfer-tokens>)
(amount-a uint)
(owner-a principal)
(token-b <can-transfer-tokens>)
(amount-b uint)
(owner-b principal)))
(begin
(unwrap! (contract-call? token-a transfer-from? owner-a owner-b amount-a))
(unwrap! (contract-call? token-b transfer-from? owner-b owner-a amount-b))))
```
Traits can either be locally defined:
```clarity
(define-trait can-transfer-tokens (
(transfer-from? (principal principal uint) (response uint)))
```
Or imported from an existing contract:
```clarity
(use-trait can-transfer-tokens
.contract-defining-trait.can-transfer-tokens)
```
Looking at trait conformance, callee contracts have two different paths. They can either be "compatible" with a trait by defining methods matching some of the methods defined in a trait, or explicitely declare conformance using the `impl-trait` statement:
```clarity
(impl-trait .contract-defining-trait.can-transfer-tokens)
```
Explicit conformance should be prefered when adequate. It acts as a safeguard by helping the static analysis system to detect deviations in method signatures before contract deployment.
The following limitations are imposed on contract calls:
1. On static dispatches, callee smart contracts _must_ exist at the time of creation.
2. No cycles may exist in the call graph of a smart contract. This prevents recursion (and re-entrancy bugs). Such structures can be detected with static analysis of the call graph, and will be rejected by the network.
3. `contract-call?` are for inter-contract calls only. Attempts to execute when the caller is also the callee will abort the transaction.

23
src/pages/fr/references/language-types.md

@ -0,0 +1,23 @@
---
title: Types
description: See a detailed list of all types for the Clarity language.
images:
large: /images/pages/write-smart-contracts.svg
sm: /images/pages/write-smart-contracts-sm.svg
---
## Clarity Type System
The type system contains the following types:
- `{label-0: value-type-0, label-1: value-type-1, ...}` - a group of data values with named fields, aka (_record_)[https://www.cs.cornell.edu/courses/cs312/2004fa/lectures/lecture3.htm].
- `(list max-len entry-type)` - a list of maximum length `max-len`, with entries of type `entry-type`
- `(response ok-type err-type)` - object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior.
- `(optional some-type)` - an option type for objects that can either be `(some value)` or `none`
- `(buff max-len)` := byte buffer of maximum length `max-len`.
- `(string-ascii max-len)` := ASCII string of maximum length `max-len`
- `(string-utf8 max-len)` := UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string")
- `principal` := object representing a principal (whether a contract principal or standard principal).
- `bool` := boolean value (`true` or `false`)
- `int` := signed 128-bit integer
- `uint` := unsigned 128-bit integer

24
src/pages/fr/references/stacking-contract.md

@ -0,0 +1,24 @@
---
title: Stacking Contract
description: See a detailed list of all functions and error codes of the Stacking contract.
---
export { convertStackingRefToMdx as getStaticProps } from '@common/data/stacking-ref'; import { StackingErrorcodeReference, StackingFunctionReference } from '@components/stacking-ref';
## Introduction
Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info).
Below is a list of public and read-only functions as well as error codes that can be returned by those methods.
## Public functions
<StackingFunctionReference {...props.mdx.publicFunctions} />
## Read-only functions
<StackingFunctionReference {...props.mdx.readonlyFunctions} />
## Error codes
<StackingErrorcodeReference {...props.mdx.errorCodes} />

513
src/pages/fr/references/stacks-node-configuration.md

@ -0,0 +1,513 @@
---
title: Stacks Node Configuration
description: Configuration parameters and options for the stacks-node binary
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Usage
```bash
stacks-node sub-command [--subcommand-option <value>]
```
## Subcommands
-> Note that the `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources.
### mocknet
Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development.
Example:
```bash
stacks-node mocknet
```
### krypton
Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](/understand-stacks/overview#proof-of-transfer-pox).
Example:
```bash
stacks-node krypton
```
### xenon
Start a node that will join and stream blocks from the public xenon testnet.
Example:
```bash
stacks-node xenon
```
### mainnet
Start a node that joins and streams blocks from the public mainnet.
Example:
```bash
stacks-node mainnet
```
### start
Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `xenon` subcommands.
#### Arguments
**--config**: relative or absolute path to the TOML config file. Required.
Example:
```bash
stacks-node start --config=/path/to/config.toml
```
See [Configuration File Options](#configuration-file-options) for more information.
#### version
Displays information about the current version and the release cycle.
Example:
```bash
stacks-node version
```
#### help
Displays a help message.
Example:
```bash
stacks-node help
```
## Configuration File Options
The TOML configuration file has multiple sections under which an option may be placed.
To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf).
### Section: node
Contains various configuration options pertaining to the stacks-node.
Example:
```toml
[node]
rpc_bind = "0.0.0.0:20443"
p2p_bind = "0.0.0.0:20444"
# Enter your private key here
seed = "replace-with-your-private-key"
miner = true
```
#### working_dir (optional)
Absolute path to the directory which the stacks-node will use for storing various data.
Example:
```toml
working_dir = "/root/stacks-node"
```
#### rpc_bind
Address and port stacks-node should bind to for RPC connections.
Example:
```toml
rpc_bind = "0.0.0.0:20443"
```
#### p2p_bind
Address and port stacks-node should bind to for P2P connections.
Example:
```toml
p2p_bind = "0.0.0.0:20444"
```
#### data_url (optional)
Address and port from which the stacks-node will be receiving incoming rpc connections.
Example:
```toml
data_url = "1.2.3.4:20443"
```
#### p2p_address (optional)
Address and port from which the stacks-node will be receiving incoming p2p connections.
Example:
```toml
p2p_address = "1.2.3.4:20444"
```
#### bootstrap_node (optional)
Public key, address, and port stacks-node should use to pull transaction data from when starting.
Example:
```toml
bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@xenon.blockstack.org:20444"
```
#### wait_time_for_microblocks (optional)
The amount of time (in milliseconds) that a node will wait before trying to mine a block, after catching up to the anchored chain tip. This gives the current leader time to broadcast microblocks that will get included in that mined block.
Example:
```toml
wait_time_for_microblocks = 15000
```
#### seed (optional)
The private key to use for mining. Only needed if `miner` is set to `true`.
[See this page for information on how to generate a private key.](/start-mining)
Example:
```toml
seed = "replace-with-your-private-key"
```
#### local_peer_seed (optional)
The private key to use for signing P2P messages in the networking stack. It differentiates network peers and is used even by non-mining nodes.
[See this page for information on how to generate a private key.](/start-mining)
Example:
```toml
local_peer_seed = "replace-with-your-private-key"
```
#### miner (optional)
Determines whether the stacks-node is running a follower (`false`) or a miner (`true`). Defaults to `false` if omitted.
[See this page for information on how to run a miner.](/start-mining)
Example:
```toml
miner = true
```
#### mine_microblocks (optional)
Determines whether the stacks-node will mine microblocks. Will only take effect if `miner` is set to `true`.
[See this page for information on how to run a miner.](/start-mining)
Example:
```toml
mine_microblocks = true
```
#### prometheus_bind (optional)
Address and port stacks-node should open for Prometheus metrics collection.
Example:
```toml
prometheus_bind = "0.0.0.0:9153"
```
### Section: events_observer (optional)
Contains options for watching events emitted by a local [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service.
-> This section can be repeated multiple times.
Example:
```toml
[[events_observer]]
endpoint = "address-to-my-local.stacks-node-api.com:3700"
retry_count = 255
events_keys = ["*"]
```
#### endpoint
Address and port to a stacks-node-api to watch for events.
Example:
```toml
endpoint = "address-to-my-local.stacks-node-api.com:3700"
```
#### retry_count
Number of times to retry sending events to the endpoint before failing.
Example:
```toml
retry_count = 255
```
#### events_keys
Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events.
Examples:
```toml
events_keys = ["*"]
```
```toml
events_keys = [
"STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.store::print",
"STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.contract.ft-token",
"STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.contract.nft-token",
"stx"
]
```
### Section: connection_options (optional)
Specifies configuration options for others connecting to the stacks node.
Example:
```toml
[connection_options]
public_ip_address = "1.2.3.4:20444"
download_interval = 60
walk_interval = 30
```
#### public_ip_address
The advertised public IP of this stacks-node.
Example:
```toml
public_ip_address = "1.2.3.4:20444"
```
#### download_interval
Time (in seconds) between attempts to download blocks.
Example:
```toml
download_interval = 60
```
#### walk_interval
Time (in seconds) between attempts to walk the neighborhood.
Example:
```toml
walk_interval = 30
```
#### read_only_call_limit_read_length
Total number of bytes allowed to be read by an individual read-only function call.
Example:
```toml
read_only_call_limit_read_length = 100000
```
#### read_only_call_limit_read_count
Total number of independent read operations permitted for an individual read-only function call.
Example:
```toml
read_only_call_limit_read_count = 30
```
#### read_only_call_limit_runtime
[Runtime cost](https://github.com/stacksgov/sips/blob/2d3fd9bf8da7a04f588d90ff6252173d7609d7bf/sips/sip-006/sip-006-runtime-cost-assessment.md#introduction) limit for an individual read-only function call.
Example:
```toml
read_only_call_limit_runtime = 1000000000
```
### Section: burnchain
This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC).
Example:
```toml
[burnchain]
chain = "bitcoin"
mode = "mainnet"
peer_host = "your.bitcoind.node.org"
rpc_port = 8332
peer_port = 8333
```
#### chain
The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `"bitcoin"`.
Example:
```toml
chain = "bitcoin"
```
#### mode
The profile or test phase of which to run stacks-node. Valid values are `"mocknet"`, `"helium"`, `"neon"`, `"argon"`, `"krypton"`, `"xenon"`.
Example:
```toml
mode = "xenon"
```
#### peer_host
Domain name of the host running the backend Bitcoin blockchain. It's required to either run a personal Bitcoin node locally, or to use a publicly hosted Bitcoin node.
Example:
```toml
peer_host = "your.bitcoind.node.org"
```
#### rpc_port
peer_host's port stacks-node will connect to for RPC connections.
Example:
```toml
rpc_port = 8332
```
#### peer_port
peer_host's port stacks-node will connect to for P2P connections.
Example:
```toml
peer_port = 8333
```
#### burn_fee_cap (optional)
Maximum amount (in Satoshis) of "burn commitment" to broadcast for the next block's leader election.
Example:
```toml
burn_fee_cap = 30000
```
#### satoshis_per_byte (optional)
Amount (in Satoshis) per [virtual byte](https://en.bitcoin.it/wiki/Weight_units). This is used to compute the transaction fees.
Example:
```toml
satoshis_per_byte = 50
```
So total transaction cost would be `(estimated_tx_size * satoshis_per_byte) + burn_fee_cap`.
#### commit_anchor_block_within (optional)
Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `"helium"`.
Example:
```toml
commit_anchor_block_within = 10000
```
### Section: ustx_balance (testnet/regtest only)
This section contains configuration options pertaining to the genesis block allocation for an address in micro-STX. If a user changes these values, their node may be in conflict with other nodes on the network and find themselves unable to sync with other nodes.
-> This section can repeat multiple times, and thus is in double-brackets. Each section can define only one address. This section is ignored if running a node on mainnet.
Example:
```toml
[[ustx_balance]]
address = "STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6"
amount = 10000000000000000
[[ustx_balance]]
address = "ST11NJTTKGVT6D1HY4NJRVQWMQM7TVAR091EJ8P2Y"
amount = 10000000000000000
[[ustx_balance]]
address = "ST1HB1T8WRNBYB0Y3T7WXZS38NKKPTBR3EG9EPJKR"
amount = 10000000000000000
[[ustx_balance]]
address = "STRYYQQ9M8KAF4NS7WNZQYY59X93XEKR31JP64CP"
amount = 10000000000000000
```
#### address
Address which maintains a micro-STX balance.
Example:
```toml
address = "STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6"
```
#### amount
The balance of micro-STX given to the address at the start of the node.
Example:
```toml
amount = 10000000000000000
```

352
src/pages/fr/start-mining/mainnet.md

@ -0,0 +1,352 @@
---
title: Mine mainnet Stacks tokens
description: Set up and run a miner on the Stacks 2.0 mainnet
icon: MainnetIcon
experience: beginners
duration: 10 minutes
tags:
- tutorial
images:
large: /images/pages/start-mining.svg
sm: /images/pages/start-mining-sm.svg
---
## Introduction
Make sure you've followed the [Running mainnet node](/understand-stacks/running-mainnet-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet.
If you're interested in mining on the testnet, you can find instructions on how to do that here:
[@page-reference | inline] | /start-mining/testnet
If you want to learn more about the technical details of mining, please review the mining guide:
[@page-reference | inline] | /understand-stacks/mining
## Running bitcoind locally
To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements)
First, download the bitcoind software for your platform from https://bitcoin.org/en/download.
Next, start bitcoind with the following configuration:
```toml
server=1
rpcuser=your-bitcoind-username
rpcpassword=your-bitcoind-password
txindex=0
listen=1
rpcserialversion=0
maxorphantx=1
banscore=1
bind=0.0.0.0:8333
rpcbind=0.0.0.0:8332
rpcport=8332
```
Finally, start bitcoind as follows:
```bash
bitcoind -conf=path/to/bitcoin.conf
```
It may take a few days for the node to synchronize with the Bitcoin mainnet.
## Running a miner
First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command.
```bash
npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt
```
After this runs, you should see some JSON in the new `keychain.txt` file that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
**Don't lose this information** - we'll need to use the `privateKey` field later on.
The above BTC address will then need to be imported into the BTC network.
```bash
bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress <btcAddress from JSON above>
```
Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
# Enter your private key here
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on mainnet, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file.
To run your miner, run this in the command line:
```bash
stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml
```
Your node should start. It will take some time to sync, and then your miner will be running.
### Creating an optimized binary
The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run:
```bash
cd testnet/stacks-node
cargo build --release --bin stacks-node
```
The above code will compile an optimized binary. To use it, run:
```bash
cd ../..
./target/release/stacks-node start --config=./mainnet-miner-conf.toml
```
For a full reference of subcommands and configuration options used by `stacks-node`, please see this page.
[@page-reference | inline] | /references/stacks-node-configuration
To read more about the technical details of mining on the Stacks 2.0 network, have a look at the minig guide:
[@page-reference | inline] | /understand-stacks/mining
### Enable debug logging
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
STACKS_LOG_DEBUG=1 stacks-node mainnet
```
## Running a miner in Windows
### Prerequisites
Make sure you've followed the [Running the mainnet node on Windows](/understand-stacks/running-mainnet-node#running-the-mainnet-node-on-windows) tutorial and [Running itcoind locally](#running-bitcoind-locally) section above before starting this tutorial.
### Generate keychain and get mainnet tokens in Windows
To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command.
Generate a keychain:
```bash
npm install --global @stacks/cli
stx make_keychain > cli_keychain.json
type cli_keychain.json
```
After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
-> Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details
The above BTC address will then need to be imported into the BTC network.
```bash
bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress <btcAddress from JSON above>
```
Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
### Update configuration file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
# Enter your private key here
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on mainnet, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Run the miner
To start your miner, run this in the command line:
```bash
stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml
```
-> **Note** : While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. ![Windows Defender](/images/windows-defender.png)
Your node should start. It will take some time to sync, and then your miner will be running.
### Enable debug logging in Windows
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
set RUST_BACKTRACE=full;
set STACKS_LOG_DEBUG=1;
stacks-node start --config=mainnet-miner-conf.toml
```
## Optional: Running with Docker
Alternatively, you can run the mainnet node with Docker.
-> Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine.
### Generate keychain and get tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null
```
We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
### Update configuration file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
# Enter your private key here
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on mainnet, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Start the miner
-> The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled
```bash
docker run -d \
--name stacks_miner \
--rm \
--network host \
-e RUST_BACKTRACE="full" \
-e STACKS_LOG_DEBUG="1" \
-v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain:latest \
/bin/stacks-node start --config /src/stacks-node/mainnet-miner-conf.toml
```
You can review the node logs with this command:
```bash
docker logs -f stacks_miner
```
## Optional: Running in Kubernetes with Helm
In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).
Ensure you have the following prerequisites installed on your machine:
- [Docker](https://docs.docker.com/get-docker/)
- [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster)
- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)
- [helm](https://helm.sh/docs/intro/install/)
### Generate keychain and get some tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null
```
We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com).
### Install the chart and run the miner
To install the chart with the release name `my-release` and run the node as a miner:
```bash
minikube start # Only run this if standing up a local Kubernetes cluster
helm repo add blockstack https://charts.blockstack.xyz
helm install my-release blockstack/stacks-blockchain \
--set config.node.miner=true \
--set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \
--set config.burnchain.mode="mainnet"
```
You can review the node logs with this command:
```bash
kubectl logs -l app.kubernetes.io/name=stacks-blockchain
```
For more information on the Helm chart and configuration options, please refer to the [chart's homepage](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).

343
src/pages/fr/start-mining/testnet.md

@ -0,0 +1,343 @@
---
title: Mine testnet Stacks tokens
description: Set up and run a miner on the Stacks 2.0 testnet
icon: TestnetIcon
experience: beginners
duration: 10 minutes
tags:
- tutorial
images:
large: /images/pages/start-mining.svg
sm: /images/pages/start-mining-sm.svg
---
## Introduction
Make sure you've followed the [Running testnet node](/understand-stacks/running-testnet-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet.
If you want to learn more about the technical details of mining, please review the mining guide:
[@page-reference | inline] | /understand-stacks/mining
## Running bitcoind locally
To participate as a miner on Xenon, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements)
First, download the bitcoind software for your platform from https://bitcoin.org/en/download.
Next, start bitcoind with the following configuration:
```toml
server=1
rpcuser=your-bitcoind-username
rpcpassword=your-bitcoind-password
testnet=1
txindex=0
listen=1
rpcserialversion=0
maxorphantx=1
banscore=1
[test]
bind=0.0.0.0:18333
rpcbind=0.0.0.0:18332
rpcport=18332
```
Finally, start bitcoind as follows:
```bash
bitcoind -conf=path/to/bitcoin.conf
```
It may take a few hours for the node to synchronize with the Bitcoin testnet.
## Running a miner
First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command, and pass `-t` to indicate that we want a testnet keychain.
```bash
npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt
```
After this runs, you should see some JSON in the new `keychain.txt` file that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
**Don't lose this information** - we'll need to use the `privateKey` field later on.
The above BTC address will then need to be imported into the BTC testnet network.
```bash
bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress <btcAddress from JSON above>
```
Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address.
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on Xenon, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file.
To run your miner, run this in the command line:
```bash
stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml
```
Your node should start. It will take some time to sync, and then your miner will be running.
### Creating an optimized binary
The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run:
```bash
cd testnet/stacks-node
cargo build --release --bin stacks-node
```
The above code will compile an optimized binary. To use it, run:
```bash
cd ../..
./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml
```
For a full reference of subcommands and configuration options used by `stacks-node`, please see this page.
[@page-reference | inline] | /references/stacks-node-configuration
To read more about the technical details of mining on the Stacks 2.0 network, have a look at the minig guide:
[@page-reference | inline] | /understand-stacks/mining
### Enable debug logging
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
STACKS_LOG_DEBUG=1 stacks-node xenon
```
## Running a miner in Windows
### Prerequisites
Make sure you've followed the [Running the testnet node on Windows](/understand-stacks/running-testnet-node#running-the-testnet-node-on-windows) tutorial before starting this tutorial.
### Generate keychain and get testnet tokens in Windows
To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain.
Generate a keychain:
```bash
npm install --global @stacks/cli
stx make_keychain -t > cli_keychain.json
type cli_keychain.json
```
After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
"keyInfo": {
"privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801",
"address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF",
"btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND",
"index": 0
}
}
```
-> Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details
Request BTC from faucet:
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address.
### Update configuration file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on Xenon, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Run the miner
To start your miner, run this in the command line:
```bash
stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml
```
-> **Note** : While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. ![Windows Defender](/images/windows-defender.png)
Your node should start. It will take some time to sync, and then your miner will be running.
### Enable debug logging in Windows
In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run:
```bash
set RUST_BACKTRACE=full;
set STACKS_LOG_DEBUG=1;
stacks-node start --config=testnet-miner-conf.toml
```
## Optional: Running with Docker
Alternatively, you can run the testnet node with Docker.
-> Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine.
### Generate keychain and get testnet tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null
```
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address.
### Update config file
Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml).
Update the following properties:
```toml
[node]
...
seed = "replace-with-your-private-key"
local_peer_seed = "replace-with-your-private-key"
...
[burnchain]
...
# To mine on Xenon, you need to run bitcoind locally
# Details can be found in above section, 'Running bitcoind locally'
peer_host = "127.0.0.1"
username = "<USERNAME>"
password = "<PASSWORD>"
...
```
Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file.
### Start the miner
-> The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled
```bash
docker run -d \
--name stacks_miner \
--rm \
--network host \
-e RUST_BACKTRACE="full" \
-e STACKS_LOG_DEBUG="1" \
-v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain:latest \
/bin/stacks-node start --config /src/stacks-node/testnet-miner-conf.toml
```
You can review the node logs with this command:
```bash
docker logs -f stacks_miner
```
## Optional: Running in Kubernetes with Helm
In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).
Ensure you have the following prerequisites installed on your machine:
- [Docker](https://docs.docker.com/get-docker/)
- [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster)
- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)
- [helm](https://helm.sh/docs/intro/install/)
### Generate keychain and get some testnet tokens
Generate a keychain:
```bash
docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null
```
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address.
### Install the chart and run the miner
To install the chart with the release name `my-release` and run the node as a miner:
```bash
minikube start # Only run this if standing up a local Kubernetes cluster
helm repo add blockstack https://charts.blockstack.xyz
helm install my-release blockstack/stacks-blockchain \
--set config.node.miner=true \
--set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step"
```
You can review the node logs with this command:
```bash
kubectl logs -l app.kubernetes.io/name=stacks-blockchain
```
For more information on the Helm chart and configuration options, please refer to the [chart's homepage](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain).

211
src/pages/fr/understand-stacks/accounts.md

@ -0,0 +1,211 @@
---
title: Accounts
description: Guide to Stacks 2.0 accounts
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Introduction
Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances.
If you want to jump right in to generate and query a new account, try this tutorial:
-> The public-key signature system used for Stacks 2.0 accounts is [Ed25519](https://ed25519.cr.yp.to/).
Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction.
-> The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account
## Creation
An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts.
!> If the seed phrase is lost, access to the associated account cannot be restored. No person or organization, including Blockstack, can recover a lost seed phrase.
The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli):
```bash
# install CLI globally
npm install --global @stacks/cli
# generate a new account and store details in a new file
# '-t' option makes this a testnet account
stx make_keychain -t > cli_keychain.json
```
`make_keychain` creates the following file:
```js
{
"mnemonic": "aaa bbb ccc ddd ...",
"keyInfo": {
"privateKey": "5a3f1f15245bb3fb...",
"address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1",
"btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1",
"wif": "L4HXn7PLmzoNW...",
"index": 0
}
}
```
-> Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details
| Field | Description |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy |
| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` |
| `keyInfo.address` | Stacks address for the account |
| `keyInfo.btcAddress` | Corresponding BTC address for the account. |
| `keyInfo.wif` | Private key of the btcAddress in compressed format. |
| `keyInfo.index` | Nonce for the account, starting at 0 |
Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain.
-> Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method.
Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used:
```js
import {
makeRandomPrivKey,
privateKeyToString,
getAddressFromPrivateKey,
TransactionVersion,
} from '@stacks/transactions';
const privateKey = makeRandomPrivKey();
// Get public key from private
const publicKey = getPublicKey(privateKey);
const stacksAddress = getAddressFromPrivateKey(
privateKeyToString(privateKey),
TransactionVersion.Testnet // remove for Mainnet addresses
);
```
A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`.
#### stacks-gen prerequisite
Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `<command>` exists in \$PATH, or in the local project binaries, and execute that. If `<command>` is not found, it will be installed prior to execution).
```
npm install -g npx
```
#### stacks-gen usage
```
npx -q stacks-gen sk --testnet
{
"phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef",
"private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901",
"public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662",
"stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C",
"stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }",
"btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8",
"wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh"
}
```
-> The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](/understand-stacks/stacking#bitcoin-address).
Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen).
## Querying
### Get Stacks (STX) balance and nonce
STX balance and nonce can be obtained through the [`GET /v2/accounts/<stx_address>`](https://docs.hiro.so/api#operation/get_account_info) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/<stx_address>'
```
Sample response:
```js
{
"balance": "0x0000000000000000002386f26f3f40ec",
"nonce": 17
}
```
-> The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding
### Get all token balances
All token balances can be obtained through the [`GET /extended/v1/address/<stx_address>/balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address/<stx_address>/balances'
```
Sample response:
```js
{
"stx": {
"balance": "0",
"total_sent": "0",
"total_received": "0"
},
"fungible_tokens": {},
"non_fungible_tokens": {}
}
```
-> Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network.
### Get all asset events
All asset events associated with the account can be obtained through the [`GET /extended/v1/address/<stx_address>/assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address/<stx_address>/assets'
```
Sample response:
```js
{
"limit": 20,
"offset": 0,
"total": 0,
"results": [
{
"event_index": 5,
"event_type": "non_fungible_token_asset",
"asset": {
"asset_event_type": "transfer",
"asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft",
"sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR",
"recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G",
"value": {
"hex": "0x0100000000000000000000000000000001",
"repr": "u1"
}
}
},
{
"event_index": 3,
"event_type": "fungible_token_asset",
"asset": {
"asset_event_type": "mint",
"asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19",
"sender": "",
"recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR",
"amount": "12"
}
}
]
}
```

110
src/pages/fr/understand-stacks/microblocks.md

@ -0,0 +1,110 @@
---
title: Microblocks
description: Guide to Stacks Microblocks
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Introduction
Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism][], Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks.
Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin.
## Transaction states
The [Stacks block production model][] is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model.
If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known.
Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle:
```
Transaction 1 is broadcast to the mempool. It has 0 confirmations.
Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known
Transaction 1 is included in the next anchor block. It has 1 confirmation.
The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations.
The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations.
...
```
Consider a similar transaction that is not included in a microblock:
```
Transaction 2 is broadcast to the mempool. It has 0 confirmations.
Transaction 2 is included in the next anchor block. It has 1 confirmation.
The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations.
The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations.
```
The lifecycles of the two transactions are similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information.
-> If a transaction is dependent on a chain state that could by altered by previous transactions with serious implications, you should carefully consider whether it should be performed using microblocks.
## Enabling microblocks
Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either.
### Transactions
Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either.
### Mining
Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks][].
## Developing with microblocks
In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative.
A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred.
### Stacks.js libraries
Stacks.js provides the [AnchorMode][] argument on transaction objects so that your application can set the microblocks preference for transactions.
### API
!> API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks.
The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide][] for more details.
## Best practices
Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended.
### Handling nonce
Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal.
### Application design
The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this.
The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application.
#### Explorers
Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state.
#### Wallets
Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state.
#### Exchanges
Continue to count confirmations, microblocks should be considered pending.
#### Applications
Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed.
[Proof-of-Transfer consensus mechanism]: /understand-stacks/proof-of-transfer
[Stacks block production model]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader
[mining microblocks]: /understand-stacks/mining#microblocks
[AnchorMode]: https://stacks-js-git-master-blockstack.vercel.app/enums/transactions.anchormode.html
[Stacks Blockchain API guide]: https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support
[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling
[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks

74
src/pages/fr/understand-stacks/mining.md

@ -0,0 +1,74 @@
---
title: Mining
description: A guide to mining on Stacks 2.0
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Introduction
This guide highlights some technical details related to mining on the Stacks 2.0 network.
## Mining frequency
A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee.
## Coinbase rewards
Miners receive coinbase rewards for blocks they win.
The reward amounts are:
- 1000 STX per block are released in the first 4 years of mining
- 500 STX per block are released during the following 4 years
- 250 STX per block are released during the following 4 years
- 125 STX per block are released from then on indefinitely.
These "halvings" are synchronized with Bitcoin halvings.
![coinbase rewards](/images/pages/coinbase-rewards.png)
## Transaction fees
Miners receive Stacks fees for transactions mined in any block they produce.
For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees.
## Reward maturity
Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours.
## Mining with proof-of-transfer
Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain.
![mining with pox](/images/pages/mining-with-pox.png)
100,000 Bitcoin blocks **after** mining begins, the PoX sunset phase begins. During this phase, an increasing proportion of the block commit must be burnt. To burn this sunset fee, the miner must send the sunset fee amount to the first output of their block commit transaction (that is, the OPRETURN output).
400,000 Bitcoin blocks after the sunset phase begins, the sunset phase ends. After this point, PoX is no longer active, and miners must burn all of their leader block commits. They do so by sending Bitcoin to the canonical burn address `1111111111111111111114oLvT2`.
## Probability to mine next block
The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt.
The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent.
While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended.
To calculate the amount of BTC to send miners should:
- Guess the price BTC/STX for the next day (100 blocks later)
- Guess the total amount of BTCs committed by all miners
## Microblocks
The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch.
If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces.
The block streaming model is described in [SIP-001][].
[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader

147
src/pages/fr/understand-stacks/network.md

@ -0,0 +1,147 @@
---
title: Network
description: Guide to the Stacks 2.0 network
icon: TestnetIcon
images:
large: /images/pages/testnet.svg
sm: /images/pages/testnet-sm.svg
---
## Tokens
Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX).
STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6).
## Fees
Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](/understand-stacks/testnet), it is set to 1 micro-STX.
Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer'
```
The API will respond with the fee rate (as integer):
```json
1
```
[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for:
- token transfers (`estimateTransfer`)
- contract deploys (`estimateContractDeploy`)
- non read-only contract calls (`estimateContractFunctionCall`)
-> For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97).
## Nonces
Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction.
Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing.
-> The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers.
When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set.
-> The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling).
## Confirmations
The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain.
The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes.
-> Transactions can also be mined in [microblocks](/understand-stacks/microblocks), reducing the latency significantly.
The block time is hardcoded and will change throughout the implementation phases of the [testnet](/understand-stacks/testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times'
```
The API will respond with the block time (in seconds):
```js
{
"testnet": {
"target_block_time": 120
},
"mainnet": {
"target_block_time": 600
}
}
```
## Read-only function calls
Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted.
However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api).
-> Read-only function calls do not require transaction fees
A read-only contract call can be done using the [`POST /v2/contracts/call-read/<stx_address>/<contract_name>/<function_name>`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read/<stx_address>/<contract_name>/<function_name>' \
--header 'Content-Type: application/json' \
--data-raw '{
"sender": "<stx_address>.<contract_name>",
"arguments": [<clarity_value>, ...]
}'
```
Sample response for a successful call:
```js
{
"okay": true,
"result": "<clarity_value>"
}
```
-> To set the function call arguments and read the result, [Clarity values](/write-smart-contracts/values) need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations
## Querying
Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api).
### Health check
The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain.
### Network info
The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint:
```bash
# for mainnet, replace `testnet` with `mainnet`
curl 'https://stacks-node-api.testnet.stacks.co/v2/info'
```
Sample response:
```js
{
"peer_version": 385875968,
"burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37",
"burn_block_height": 1972,
"stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64",
"stable_burn_block_height": 1971,
"server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]",
"network_id": 2147483648,
"parent_network_id": 3669344250,
"stacks_tip_height": 933,
"stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f",
"stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc",
"unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae",
"exit_at_block_height": 28160
}
```

70
src/pages/fr/understand-stacks/overview.md

@ -0,0 +1,70 @@
---
title: Overview
description: Learn more about the Stacks 2.0 blockchain
icon: TestnetIcon
images:
large: /images/nodes.svg
sm: /images/nodes.svg
---
## Introduction
Stacks 2.0 is a layer-1 blockchain that connects to Bitcoin and brings smart contracts and decentralized apps to it. Smart contracts and apps developed on the Stacks platform are natively integrated with the security, stability, and economic power of Bitcoin.
## Capabilities
Read more about the features provided by the Stacks 2.0 blockchain.
-> Check out the [technical specifications](/understand-stacks/technical-specs) for a brief overview
A detailed [comparison of the Stacks blockchain to other blockchain technologies][] is available at the Stacks Foundation blog.
### Consensus mechanism
Stacks 2.0 implements a new mining mechanism called Proof of Transfer ("PoX"). PoX is a consensus algorithm between two blockchains. It uses an established blockchain (in this case Bitcoin) to secure a new blockchain (Stacks).
PoX connects to Bitcoin with a 1:1 block ratio, meaning anything that happens on the Stacks blockchain can be verified on the Bitcoin Blockchain.
Instead of burning electricity on proof of work, PoX reuses already minted bitcoins as "proof of computation" and miners represent their cost of mining in bitcoins directly.
[@page-reference | inline] | /understand-stacks/proof-of-transfer
### Mining
Mining is required to make the network usable, trustworthy, and secure. Miners verify incoming transactions, participate in the consensus mechanism, and write new blocks to the blockchain.
To incentivize mining, miners receive freshly minted Stacks (STX) tokens if they win the bid for becoming the leader of the next round.
[@page-reference | inline] | /understand-stacks/mining
### Stacking
Bitcoins used for miner bids are sent to a set of specific addresses corresponding to Stacks (STX) tokens holders that are actively participating in consensus ("Stackers"). Thus, rather than being destroyed, the bitcoins consumed in the mining process go to productive Stacks holders as a reward based on their holdings of Stacks and participation in the Stacking algorithm.
Stackers have to lock up their Stacks (STX) tokens for a certain period of time.
[@page-reference | inline] | /understand-stacks/stacking
### Smart contracts
Clarity is a new language for smart contracts on the Stacks 2.0 blockchain. The Clarity smart contract language optimizes for predictability and security.
Stacks 2.0 anchors clarity smart contracts to Bitcoin making it possible for smart contracts to operate based on actions seen on the bitcoin blockchain.
-> The [Clarity open-source project](https://clarity-lang.org/) is supported by Stacks and [Algorand](https://www.algorand.com/)
Clarity is distinct from other languages designed for writing smart contracts in a few ways:
- **Predictability**: The Clarity language uses precise and unambiguous syntax that allows developers to predict exactly how their contracts will be executed.
- **Security**: The Clarity language allows users to supply their own conditions for transactions that ensure that a contract may never unexpectedly transfer a token owned by a user.
- **No compiler**: Contracts written in Clarity are broadcasted on the Stacks blockchain exactly as they are written by developers. This ensures that the code developers wrote, analyzed, and tested, is exactly what gets executed.
[@page-reference | inline] | /write-smart-contracts/overview
## Guides
Read one of our guides to understand the ins and outs of the Stacks 2.0 blockchain.
[@page-reference | grid-small] | /understand-stacks/accounts, /understand-stacks/transactions, /understand-stacks/network, /understand-stacks/microblocks
[comparison of the Stacks blockchain to other blockchain technologies]: https://stacks.org/stacks-blockchain

57
src/pages/fr/understand-stacks/proof-of-transfer.md

@ -0,0 +1,57 @@
---
title: Proof of Transfer
description: Understand the proof-of-transfer consensus mechanism
icon: TestnetIcon
images:
large: /images/stacking.svg
sm: /images/stacking.svg
---
## Overview
Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network.
Popular consensus mechanisms in modern blockchains include proof-of-work, in which nodes dedicate computing resources, and proof-of-stake, in which nodes dedicate financial resources to secure the network.
Proof-of-burn is a novel consensus mechanism where miners compete by ‘burning’ (destroying) a proof-of-work cryptocurrency as a proxy for computing resources.
Proof-of-transfer (PoX) is an extension of the proof-of-burn mechanism. PoX uses the proof-of-work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof-of-burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network.
![PoX mechanism](/images/pox-mechanism.png)
This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, proof-of-transfer blockchains are anchored on their chosen proof-of-work chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain.
![PoX participants](/images/pox-participants.png)
## Why Bitcoin?
There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade.
Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the proof-of-transfer consensus mechanism.
SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md).
![btc-stacks](/images/pox-why-bitcoin.png)
## Blocks and microblocks
The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network.
However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin.
![stx-microblock](/images/stx-microblocks.png)
## Unlocking Bitcoin capital
Stacks also unlocks the hundreds of billions in capital in Bitcoin, and gives Bitcoiners new opportunities to use and earn BTC. Stacks is a accompaniment to the Bitcoin ecosystem, and the two networks working in tandem enables totally novel ways of using BTC. The Stacks ecosystem makes interactive cryptocurrency applications available to Bitcoin holders. Additionally, By stacking STX tokens and participating in the PoX consensus mechanism, users have the opportunity to earn BTC while securing the Stacks chain.
![Unlocking Bitcoin](/images/pox-unlocking-btc.png)
## Clarity and the Bitcoin state
Clarity smart contracts also have unique visibility into the state of the Bitcoin blockchain. This means that contract logic in a Clarity file has the ability to trigger when specific Bitcoin transactions are confirmed. Clarity smart contracts have a built in Simple Payment Verification (SPV) proofs for Bitcoin that make interacting with Bitcoin’s state much simpler for developers. Additionally, Clarity contracts can fork with the original Bitcoin chain. Therefore, in an edge case where Bitcoin forks, developers wouldn’t have to worry about adjusting the deployment of their smart contracts.
## See also
- [Read the full PoX whitepaper](https://community.stacks.org/pox)
- [Watch CEO Muneeb Ali and Evangelist Joe Bender give an overview of Stack's breakthrough PoX mining mechanism](https://www.youtube.com/watch?v=NY_eUrIcWOY)

188
src/pages/fr/understand-stacks/running-mainnet-node.md

@ -0,0 +1,188 @@
---
title: Running a mainnet node
description: Set up and run a mainnet node with Docker
icon: MainnetIcon
duration: 15 minutes
experience: beginners
tags:
- tutorial
images:
large: /images/pages/mainnet.svg
sm: /images/pages/mainnet-sm.svg
---
## Introduction
This procedure demonstrates how to run a local mainnet node using Docker images.
-> This procedure focuses on Unix-like operating systems (Linux and MacOS). This procedure has not been tested on Windows.
## Prerequisites
Running a node has no specialized hardware requirements. Users have been successful in running nodes on Raspberry Pi boards and other system-on-chip architectures. In order to complete this procedure, you must have the following software installed on the node host machine:
- [Docker](https://docs.docker.com/get-docker/)
- [curl](https://curl.se/download.html)
- [jq](https://stedolan.github.io/jq/download/)
### Firewall configuration
In order for the API node services to work correctly, you must configure any network firewall rules to allow traffic on the ports discussed in this section. The details of network and firewall configuration are highly specific to your machine and network, so a detailed example isn't provided.
The following ports must open on the host machine:
Ingress:
- stacks-blockchain (open to `0.0.0.0/0`):
- `20443 TCP`
- `20444 TCP`
Egress:
- `8332`
- `8333`
- `20443-20444`
These egress ports are for syncing [`stacks-blockchain`][] and Bitcoin headers. If they're not open, the sync will fail.
## Step 1: initial setup
In order to run the mainnet node, you must download the Docker images and create a directory structure to hold the persistent data from the services. Download and configure the Docker images with the following commands:
```sh
docker pull blockstack/stacks-blockchain
```
Create a directory structure for the service data with the following command:
```sh
mkdir -p ./stacks-node/{persistent-data/stacks-blockchain/mainnet,config/mainnet} && cd stacks-node
```
## Step 2: running Stacks blockchain
First, create the `./config/mainnet/Config.toml` file and add the following content to the file using a text editor:
```toml
[node]
working_dir = "/root/stacks-node/data"
rpc_bind = "0.0.0.0:20443"
p2p_bind = "0.0.0.0:20444"
bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444"
wait_time_for_microblocks = 10000
[burnchain]
chain = "bitcoin"
mode = "mainnet"
peer_host = "bitcoin.blockstack.com"
username = "blockstack"
password = "blockstacksystem"
rpc_port = 8332
peer_port = 8333
[connection_options]
read_only_call_limit_write_length = 0
read_only_call_limit_read_length = 100000
read_only_call_limit_write_count = 0
read_only_call_limit_read_count = 30
read_only_call_limit_runtime = 1000000000
```
Start the [`stacks-blockchain`][] container with the following command:
```sh
docker run -d --rm \
--name stacks-blockchain \
-v $(pwd)/persistent-data/stacks-blockchain/mainnet:/root/stacks-node/data \
-v $(pwd)/config/mainnet:/src/stacks-node \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain \
/bin/stacks-node start --config /src/stacks-node/Config.toml
```
You can verify the running [`stacks-blockchain`][] container with the command:
```sh
docker ps --filter name=stacks-blockchain
```
## Step 3: verifying the services
-> The initial burnchain header sync can take several minutes, until this is done the following commands will not work
To verify the [`stacks-blockchain`][] burnchain header sync progress:
```sh
docker logs stacks-blockchain
```
The output should be similar to the following:
```
INFO [1626290705.886954] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.2% (8000 out of 691034)
INFO [1626290748.103291] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.4% (10000 out of 691034)
INFO [1626290776.956535] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.7% (12000 out of 691034)
```
To verify the [`stacks-blockchain`][] tip height is progressing use the following command:
```sh
curl -sL localhost:20443/v2/info | jq
```
If the instance is running you should recieve terminal output similar to the following:
```json
{
"peer_version": 402653184,
"pox_consensus": "89d752034e73ed10d3b97e6bcf3cff53367b4166",
"burn_block_height": 666143,
"stable_pox_consensus": "707f26d9d0d1b4c62881a093c99f9232bc74e744",
"stable_burn_block_height": 666136,
"server_version": "stacks-node 2.0.11.1.0-rc1 (master:67dccdf, release build, linux [x86_64])",
"network_id": 1,
"parent_network_id": 3652501241,
"stacks_tip_height": 61,
"stacks_tip": "e08b2fe3dce36fd6d015c2a839c8eb0885cbe29119c1e2a581f75bc5814bce6f",
"stacks_tip_consensus_hash": "ad9f4cb6155a5b4f5dcb719d0f6bee043038bc63",
"genesis_chainstate_hash": "74237aa39aa50a83de11a4f53e9d3bb7d43461d1de9873f402e5453ae60bc59b",
"unanchored_tip": "74d172df8f8934b468c5b0af2efdefe938e9848772d69bcaeffcfe1d6c6ef041",
"unanchored_seq": 0,
"exit_at_block_height": null
}
```
## Stopping the mainnet node
Use the following commands to stop the local mainnet node:
```sh
docker stop stacks-blockchain
```
## Optional. Run stacks node with own bitcoin node
It's encouraged to use your own bitcoin node when possible.
To do this simply update the `stacks-node/config/mainnet/Config.toml` file with the details of your bitcoin node. For example:
```
[burnchain]
chain = "bitcoin"
mode = "mainnet"
peer_host = "localhost"
username = "rpc username"
password = "rpc password"
rpc_port = 8332
peer_port = 8333
```
The rpc configuration of your bitcoin node is out of the scope of this document, but you can find more information on how to set it up [here](https://developer.bitcoin.org/examples/intro.html).
## Additional reading
- [Running an API instance with Docker][]
[Running an API instance with Docker]: https://docs.hiro.so/get-started/running-api-node
[`stacks-blockchain`]: https://github.com/stacks-network/stacks-blockchain

141
src/pages/fr/understand-stacks/running-testnet-node.md

@ -0,0 +1,141 @@
---
title: Running a testnet node
description: Set up and run a testnet node with Docker
icon: TestnetIcon
duration: 15 minutes
experience: beginners
tags:
- tutorial
images:
large: /images/cli.svg
sm: /images/cli.svg
---
## Introduction
This procedure demonstrates how to run a local testnet node using Docker images.
-> This procedure focuses on Unix-like operating systems (Linux and MacOS). This procedure has not been tested on Windows.
## Prerequisites
Running a node has no specialized hardware requirements. Users have been successful in running nodes on Raspberry Pi boards and other system-on-chip architectures. In order to complete this procedure, you must have the following software installed on the node host machine:
- [Docker](https://docs.docker.com/get-docker/)
- [curl](https://curl.se/download.html)
- [jq](https://stedolan.github.io/jq/download/)
### Firewall configuration
In order for the API node services to work correctly, you must configure any network firewall rules to allow traffic on the ports discussed in this section. The details of network and firewall configuration are highly specific to your machine and network, so a detailed example isn't provided.
The following ports must open on the host machine:
Ingress:
- stacks-blockchain (open to `0.0.0.0/0`):
- `20443 TCP`
- `20444 TCP`
Egress:
- `18332`
- `18333`
- `20443-20444`
These egress ports are for syncing [`stacks-blockchain`][] and Bitcoin headers. If they're not open, the sync will fail.
## Step 1: initial setup
In order to run the testnet node, you must download the Docker images and create a directory structure to hold the persistent data from the services. Download and configure the Docker images with the following commands:
```sh
docker pull blockstack/stacks-blockchain
```
Create a directory structure for the service data with the following command:
```sh
mkdir -p ./stacks-node/persistent-data/stacks-blockchain/testnet && cd stacks-node
```
## Step 2: running Stacks blockchain
Start the [`stacks-blockchain`][] container with the following command:
```sh
docker run -d --rm \
--name stacks-blockchain \
-v $(pwd)/persistent-data/stacks-blockchain/testnet:/root/stacks-node/data \
-p 20443:20443 \
-p 20444:20444 \
blockstack/stacks-blockchain \
/bin/stacks-node xenon
```
You can verify the running [`stacks-blockchain`][] container with the command:
```sh
docker ps --filter name=stacks-blockchain
```
## Step 3: verifying the services
-> The initial burnchain header sync can take several minutes, until this is done the following commands will not work
To verify the [`stacks-blockchain`][] burnchain header sync progress:
```sh
docker logs stacks-blockchain
```
The output should be similar to the following:
```
INFO [1626290705.886954] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.2% (8000 out of 2034380)
INFO [1626290748.103291] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.4% (10000 out of 2034380)
INFO [1626290776.956535] [src/burnchains/bitcoin/spv.rs:926] [main] Syncing Bitcoin headers: 1.7% (12000 out of 2034380)
```
To verify the [`stacks-blockchain`][] tip height is progressing use the following command:
```sh
curl -sL localhost:20443/v2/info | jq
```
If the instance is running you should recieve terminal output similar to the following:
```json
{
"peer_version": 4207599105,
"pox_consensus": "12f7fa85e5099755a00b7eaecded1aa27af61748",
"burn_block_height": 2034380,
"stable_pox_consensus": "5cc4e0403ff6a1a4bd17dae9600c7c13d0b10bdf",
"stable_burn_block_height": 2034373,
"server_version": "stacks-node 2.0.11.2.0-rc1 (develop:7b6d3ee+, release build, linux [x86_64])",
"network_id": 2147483648,
"parent_network_id": 118034699,
"stacks_tip_height": 509,
"stacks_tip": "e0ee952e9891709d196080ca638ad07e6146d4c362e6afe4bb46f42d5fe584e8",
"stacks_tip_consensus_hash": "12f7fa85e5099755a00b7eaecded1aa27af61748",
"genesis_chainstate_hash": "74237aa39aa50a83de11a4f53e9d3bb7d43461d1de9873f402e5453ae60bc59b",
"unanchored_tip": "32bc86590f11504f17904ee7f5cb05bcf71a68a35f0bb3bc2d31aca726090842",
"unanchored_seq": 0,
"exit_at_block_height": null
}
```
## Stopping the testnet node
Use the following commands to stop the local testnet node:
```sh
docker stop stacks-blockchain
```
## Additional reading
- [Running an API instance with Docker][]
[Running an API instance with Docker]: https://docs.hiro.so/get-started/running-api-node
[`stacks-blockchain`]: https://github.com/stacks-network/stacks-blockchain

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save