In this article, you will learn how to integrate Stratis into your Python application using Startis Blockchain Python SDK, pyStratis. It is recommended to go through the following:
- What Is Blockchain
- Write Your First Smart Contract On Stratis Blockchain
- Do You Need A Blockchain
Stratis Platform
Stratis Ltd. is the creator of Stratis Platform, a blockchain technology platform for enterprises to build enterprise-grade blockchain-based solutions using Microsoft’s .NET framework and C# language. Stratis Platform is easy to learn, adapt, and integrate with existing enterprise applications. Stratis offers both public blockchain and private blockchain solutions. Stratis’s product offerings include Distributed Ledger Technology (DLT), Identity Platform, Supply Trust, STO Platform, DiFi, and Smart Contracts written in C# and executed on native .NET CLR makes it appealing to companies that want to build blockchain solutions on Microsoft stack.
Visit here to learn more about Stratis Platform.
Blockchain Full Node
In a distributed network, there are a lot of computers connected. Each computer is called a node. A node is a point of intersection or connection within the network. It can act as both a redistribution point or a communication endpoint. A Blockchain full node is a node on a Blockchain network.
Every block and transaction is downloaded and checked against Blockchain's consensus rules by full nodes. Even if every other node on the network considers a transaction or block is acceptable, it is rejected if it defies the consensus rules. Miners have limited power on full nodes: they can only rearrange or delete transactions, and only with a lot of computational power. Although a powerful miner may carry out certain major assaults, full nodes rely on miners for just a few things, therefore miners cannot fully modify or destroy the Blockchain.
To know about Stratis Full Node, visit here.
pyStratis
pyStratis enables Python Developers to begin utilizing Stratis Blockchain Technologies in a programming language they are already familiar with. Python is renowned as one of the most widely used programming languages globally. With the development of Python SDK, enthused developers can now begin to leverage Stratis Blockchain Technologies with ease.
Building and signing transactions, dealing with Smart Contracts and getting a blockchain state are all simple tasks that pyStratis can handle. The STRAX Blockchain as well as the Cirrus Sidechain are also fully supported. InterFlux Hub functionality has also been added to allow transactions between Stratis and other blockchains, such as Ethereum.
You can visit pyStratis GitHub to learn more.
ReadTheDocs API documentation can be found at http://pystratis.readthedocs.io.
How to install pyStratis
1. From the Python Package Index (PyPi)
2. Most recent (from GitHub)
3. Install from PyPi with test dependencies
pyStratis provides a python interface to a running Strax or Cirrus node's API. Therefore, to use pyStratis, you will need a running node daemon.
Strax Core
Strax is the main chain of the Stratis Blockchain. Stratis Core has been updated to fully support transfers to the Cirrus Sidechain, as well as incorporating the latest release of the Stratis Full Node.
The most up-to-date version of the Strax Wallet can be found at https://github.com/stratisproject/StraxUI/releases/.Clone the repository from GitHub, check out the latest release, and enter the directory.
The node daemon can be started with dotnet run
.
- Configuration settings can be updated in the stratis.conf file in the data directory or through command line args.
- Important (optional) args:
-txindex=1
For retrieving individual transaction details. Needed for some API calls.-addressindex=1
For retrieving balance details for individual addresses. Needed for some API calls.-apiuri=0.0.0.0
If node is being run on a remote device on your network (i.e. headless RPi) to access API outside of ssh tunnel.-datadir=<custom datadir path>
Change your node's data directory.-testnet
Connect the node to the testnet blockchain.-regtest
Regression testing network.-port=12344
Change the default connection port.-apiport=12345
Change the api port.-rpcport=12346
Change the rpc port (if active, inactive by default).-signalrport=12347
Change the signalrport.- Other arguments can be discovered in the stratis.conf file or by running the
dotnet run help
command.
We use the following code to initialize Strax Node
Visit StraxNode to learn more.
Cirrus Core
Cirrus is the sidechain of the Stratis Blockchain. Cirrus tokens are pegged 1:1 with Strax. Cirrus Core wallet, allowing users to create and manage a wallet, interact with Smart Contracts, deploy Smart Contracts and perform cross-chain transfers back to the Stratis Mainchain.
The most up-to-date version of the Cirrus Wallet can be found at https://github.com/stratisproject/CirrusCore/releases/..
Clone the repository from GitHub, check out the latest release, and enter the directory.
The node daemon can be started with dotnet run
.
We use the following code to initialize Cirrus Node
Visit CirrusNode to learn more.
Interflux Gateway (Multisig Masternodes)
- InterfluxStraxNode - The Strax member of the multisig Interflux Gateway pair.
- InterfluxCirrusNode - The Cirrus member of the multisig Interflux Gateway pair.
Standard Masternodes
- StraxMasterNode - The Strax member of the standard masternode pair.
- CirrusMasterNode - The Cirrus member of the standard masternode pair.
Node API endpoints
The following are the responsibilities and functions of an Endpoint Node.
- Data on the blockchain should be synchronized
- Validate the newly received blocks
- Responds to query requests
- Transaction requests are sent to the Proxy Nodes
At this point, you should have:
- A running node daemon.
- An initialized pystratis.node instance.
Active API routes are implemented as class properties.
API endpoints can be called as in the following example:
Please see the pystratis.api namespace documentation for more information on calling specific API endpoints.
pyStratis Encryption Keys
Blockchain technology uses cryptographic hashing algorithms to implement data immutability. That means, once data is written on a blockchain database, no one can modify or change it. Previous hash and consensus mechanisms make tampering with a block’s data very hard.
Blockchain technology uses cryptography to encrypt any sensitive data. Users on the system are anonymous and it uses private and public key combinations in data authentication.
To read more about Cryptography, visit
pystratis.core provides basic key functionality common among cryptocurrency platforms.
The function used in cryptography examples
- Key() is used to apply the hash function on the given data
- get_bytes() converts the given hexadecimal string into binary string
- wif_key() converts the given data into Wallet Import Format(WIF). WIF also known as a Wallet Export Format is a method of encoding a private ECDSA key to make it easier to copy.
- ExtKey() is used to generate the extended private key
- ExtPubKey() is used to generate the extended public key
- generate_private_key_bytes() is used to get private key from this extended private key
- generate_chain_code_bytes() is used to get chain code from this extended private key.
- PubKey() is used to generate a compressed public key
- uncompressed() results in an uncompressed public key
You can read more at pyStratis.Core
In the following way, you can generate and use Private Key
Private key
Extended private key
An extended private key is the combination of a private key and chain code and can be used to derive child private keys (and from them, child public keys)
In the following way, you can generate and use Public Key
Public key
Extended public key
An extended public key is a public key and chain code, which can be used to create child public keys.
pystratis.core.types
C# integer representations do not exist in Python. pystratis.core.types define several types to facilitate compatibility with the C# StratisFullNode while ensuring overflow protection.
pystratis.core.types include:
- int32, uint32
- int64, uint64
- uint128, uint160, uint256
Money
- Money is represented in pystratis as a custom type and stored under the hood as a decimal. Decimal value in Coin units.
- The class method
Money.from_satoshi_units()
handles conversion from satoshi units to Coin units. - The instance method
to_coin_unit()
represents Money as a string with 8 decimal places.
Address
Misspelling an address is a common cause of lost funds across cryptocurrency networks. The Address
type was created to prevent this error by validating the string representation of the address using the provided network. ddress
can validate p2pkh, p2sh, p2wpkh, and p2wsh addresses on Strax and Cirrus networks.
Networks supported:
- StraxMain, StraxTest, StraxRegTest
- CirrusMain, CirrusTest, CirrusRegTest
- Ethereum.
hexstr
The hexstr
type is a string subclass that restricts inputs to the 0123456789abcdef
hexadecimal charset.
Using Strax Wallet through pyStratis
A cryptocurrency wallet is a hardware device, software application, or service that keeps the public and/or private keys for cryptocurrency transactions. A cryptocurrency wallet usually includes the ability to encrypt and/or sign information in addition to the fundamental function of holding keys. Signing can result in the execution of a smart contract, a cryptocurrency transaction, identification, or the legally signing of a "document". Learn more here
To be able to run a wallet, you need to have Stratis FullNode running on your machine. You can learn more about FullNode here.
Creating a wallet
Loading a wallet
Recovering a wallet
Listing wallets
Creating an account
Listing wallet accounts
Getting an unused address
Getting all addresses
Getting general information about a wallet
Getting a wallet history
Resyncing wallet
Getting the balance of a wallet
To learn more about using Strax wallet through pyStratis, visit here.
Signing and verifying a message
Retrieving spendable utxo
The spendable_transactions method returns a SpendableTransactionsModel, which contains a list of SpendableTransactionModel.
Building and signing a transaction
Building a transaction means creating a block on the blockchain, and signing a transaction means adding the newly created block as a new node after validating.
The following code shows how we can send a transaction to an unused address on our node.
Offline signing
The technique of maintaining private keys on an offline device (not connected to the internet) and signing on individual transactions are referred to as "offline transactions." The signature is then copied and pasted onto another connected device before being broadcast into the Bitcoin network.
Offline signing is used mainly to prevent any unauthorized access to the network, which may hamper the network.
Using the same s_txs
, amount_to_send
, destination_address
, and change_address
as the last example, we are going to build a transaction that can be signed offline.
Once the offline sign request is built, you'll need to do the next step on your offline device. We'll use pydantic
it to help move our data to the offline device for signing.
First, you'll need to serialize the response from the API request.
The next steps assume you are on the offline device (this should be done with swagger or the UI, but including here for completeness, so that you can understand the complete process).
Back on the online node, time to broadcast the transaction.
Deploying a Smart Contract with pyStratis
A smart contract is a self-executing contract in which the conditions of the buyer-seller agreement are encoded directly into lines of code. The code, as well as the agreements, are disseminated throughout a decentralized blockchain network. Transactions are trackable and irreversible, and the programming regulates their execution. Smart contracts eliminate the requirement for a central authority, legal system, or external enforcement mechanism to carry out trustworthy transactions and agreements between distant, anonymous participants.
This section will demonstrate how to use pystratis to deploy and call a smart contract on the Cirrus network, we will use the CirrusTest testnet. The contract C# code and corresponding bytecode for this example can be found on Github here.
In the following code, I am using a pre-created smart contract, you can learn to create a smart contract here. To dive more and create a voting smart contract, you can visit here.
With the above code, we import the required libraries.
In the above code, we do 3 things. First, we will create an instance of CirrusTest, then assign the contract bytecode, and then set up our wallet.
In the above code, we build a demo transaction. I have used recommended values for both gas price and gas limit. Gas refers to the fee, or pricing value, required to successfully conduct a transaction or execute a contract on the Stratis blockchain platform. You can learn more about Gas Prices, here.
In the above code, before deploying the smart contract, we need to test it on a local machine. In order to test, we create a local call, to test our contract. We do this by calling "TestMethod", which persists a message string at a specified integer index. Since we are not passing any wallet name, hence we don't have a risk of losing Strax. This is similar to what we do in C# using SCT Tool.
From Stratis documentation,
“A contract call uses a regular transaction that is broadcast to the network. The call parameters are encapsulated in the transaction and handled by the network in the same way as any other transaction. Every node in the network will execute a contract call. If a contract call modifies the state database, the global state is changed.
A local call does not require a transaction. Instead, it passes the call data directly to the local node and executes it on the local machine only. A local call runs against a copy of the state database. If the local call makes changes to the state, these changes are discarded after execution.
Local calls can be used to read the contract state without expending gas (to query the value of a property for example). A local call can also aid in estimating gas costs without needing to broadcast transactions to the main network.”
Once we are certain about the performance of the contract, we are all set to deploy it on the test net or main net, whichever suits you. Since we will be deploying, hence we are not required to make a local call.
We use node.smart_contract_wallet.create() to create and deploy the smart contract.
In the above code, we make a call, and this time we pass the wallet details, unlike a local call, this call will cost us Strax.
To learn more about the methods used in this section, visit Smart Contacts and Smart Contract Wallet.
No comments:
Post a Comment