Category: Blockchain

Bitcoin Notes

Bitcoin is a internet of money. Invented in 2008. Started in 2009

Bitcoin consists of –

  • Bitcoin Protocol – A denetralized peer-to-peer network
  • Blockchain – Public transaction ledger
  • Consensus rule – Set of rules for independent transaction validation and currency issuance
  • Proof-of-Work – Distributed computation system.

Mining– A decentralized mathematical and deterministic currency issuance. Competing to find solutions to a mathematical problem while processing bitcoin transactions (power to verify and record transactions) which is done every 10 minutes.

The mining process serves two purposes
in bitcoin:

  • Mining nodes validate all transactions by reference to bitcoin’s consensus rules.
    Therefore, mining provides security for bitcoin transactions by rejecting invalid
    or malformed transactions.
  • Mining creates new bitcoin in each block, almost like a central bank printing new
    money. The amount of bitcoin created per block is limited and diminishes with
    time, following a fixed issuance schedule

Transaction script – A decentralized transaction verification system.

Paper title – “Bitcoin: A Peer-to-Peer Electronic Cash System” written by Satoshi Nakamoto.

Fast, Secure and Borderless. Distributed, peer-to-peer system. No central server or point of control. Created through a process called as mining.

Bitcoin is completerly decentralised by design and free of any central authority or point of control that can be attacked or corrupted.

Every 10 minutes or so, Mining computers compete against thousands of similar systems in a global race to find a solution to a block of transactions. Finding such a solution, the so called Proof-of-Work (PoW)

Fixed total 21 millions coins will be created by the year 2140.

Bitcoin is virtual. User of bitcoin own keys that allow then to prove ownership stored in digital wallet.

Application Specific Integrated Circuits (ASIC)

Unverified transactions when included in a new block it is called as candidate block.

Bitcoin Improvement Proposal

Important Notes-

  • Bitcoin currency will defalte in long term as the rate of issuance will reduce and ultimately diminish.
  • Bitcoin is not a physical or digital coins. The coins are implied in transactions that can be transfered from sender to receipient.
  • Bitcoin users can transfer funds using the keys that a re stored in digital wallet/ledger. They need to sign a tranasction to unlock the value and spend it by transfering the funds. key that can sign the transactions is the only pre-requisite to spend bitcoin.

Types of wallets-

  • Desktop Wallet
  • Mobile Wallet
  • Web Wallet
  • Hardware signing devices (Harware wallet – most secure)

Full node versus lightweight

  • Full node – offers complete autonomy to its users (self governance)
  • Lightweight client. simplified-payment-verification (SPV)
  • Third-party API client

Abbrevations –

  • SPV – Simplified Payment Verification
  • NFC – Near field communication
  • POW – Proof of work
  • P2P – peer-to-peer network

Computing problems –

  • Byzantine Generals problem – consensus between various parties without a leader in distributed computing

Alogrithms-

  • proof-of-work algorithm (pow)

Setup BTCPay server in Azure

BTCPay Server is a self-hosted, open-source cryptocurrency payment processor. It’s secure, private, censorship-resistant and free.

Refer this link

Create a Resource group in Azure. I create this in West Us region.

Choose the template from the provided link and should take straight to your Azure subscription-

Enter the valid Vm Size and the supported crypto payment.

Select the Network – Mainnet, TestNet or regtest

Select the Ubuntu version. You may select the latest

Resources in Azure

This should create following resources in Azure in the selected resource group-

Navigate to BTCPayServerPublicIP resource. This should show the dns name.

This is your BTC pay admin portal.

Register Admin user

First time when you access the Btc Pay server should ask you to register a user. This user will be a owner.

Login to BTC pay server

Login with the newly created user

You will be asked to configure the lightining network and create a wallet.

Configuring the wallet and lightning network will follow in next blog along with integration with integration with commerce system such as Order Cloud.

Stay tuned to know how to configure this which should ulitmately sync the nodes as shown in below screen.

Loading

Indexing Bitcoin Transaction Database

By default Bitcoin Core builds a database containing only the transactions for the user’s wallet.

Wallet transactions can be retireved using JSON RPC API gettransaction command.

But if you want to retrieve any transaction within the node use command getrawtransaction. This command will search transactions in the index.

bitcoin.conf file set txindex

Bitcoin daemon or GUI uses conf file to load settings. On the first bitcoind run it will ask to create a config file.

Set txindex=1 in the config file before running the daemon. If the indexing is enabled the bitcoin daemon then should start synching the blocks and index.

bitcond -reindex option

If the txindex is not set in config before the first run and if later you want to index the database use -reindex option.

Re-index should take a while. To improve perfromance disable -printtoconsole option

bitcoind -reindex -rpcuser=xxxx -rpcpassword=xxxxx

bitcond -txindex option

If the txindex is not set in config before the first run and if later you want to index the database use -txindex option.

bitcoind -txindex -rpcuser=xxxx -rpcpassword=xxxxx

Bitcoin FAQs

How much Satoshi is 1 Bitcoin?

One Hundred Million Satoshi(Sats) is 1 Bitcoin

100000000 Satoshi = 1 Bitcoin

Satoshi to Bitcoin Conversion

SatoshiBitcoin
1 Satoshi (One)(1/100,000,000th)0.00000001 Bitcoin
10 Satoshi (Ten)0.00000010 Bitcoin
100 Satoshi (One Hundred)0.00000100 Bitcoin
1,000 Satoshi (One Thousand)0.00001000 Bitcoin
10,000 Satoshi (Ten Thousand)0.00010000 Bitcoin
100,000 Satoshi ( One Hundred Thousand)0.00100000 Bitcoin
1,000,000 Satoshi ( One Million)0.01000000 Bitcoin
10,000,000 Satoshi (Ten Million)0.10000000 Bitcoin
100,000,000 Satoshi (One Hundred Million)1.00000000 Bitcoin

How to start daemon in background?

To run Bitcoin in background as a process, start the bitcoind with daemon option.

bitcoind -daemon

Popular blockchain explorers-

Bitcoin Block Explorer

BlockCypher Explorer

blockhain.info

Bitpay Insight

mempool space

In these explorer you can search by transaction hash, address, block number and block hash

Loading

Run Bitcoin full test node in Linux

This installation is performed on freshly installed Ubuntu system.

sudo apt update
snap install bitcoin-core

This should install Bitcoin Core on Ubuntu machine-

But lets not use GUI for this and setup test node using Bitcoin Daemon.

Bitcoin daemon should be installed in root folder and the executable can be found on this path- /snap/bitcoin-core/141/bin

Use below command to find the version of the daemon-

bitcoin-core.daemon --version

Run command –

bitcoin-core.daemon

Here the last line its expecting a bitcoin.conf file in location- /home/sandy/snap/bitcoin-core/common/.bitcoin/bitcoin.conf. This oath might be different for you.

Create a bitcoin.conf file at this location and paste in following to configure bitcoin daemon to run in test node.

Set the chain=test

set path to blocksdir and datadir

set txindex=1 to index the transaction

Set rpcuser and rpcpassword to use JSON rpc api

server=1 tells Bitcoin-QT to accept JSON-RPC commands.

# [chain]
# Test Network.
chain=test

# [core]
# Specify a non-default location to store blockchain data.
blocksdir=/home/sandy/snap/bitcoin-core/common/.bitcoin
# Specify a non-default location to store blockchain and other data.
datadir=/home/sandy/snap/bitcoin-core/common/.bitcoin

# Options only for mainnet
[main]

# Options only for testnet
[test]

# Options only for regtest
[regtest]

txindex=1

server=1

rpcuser=your_rpc_user
rpcpassword=your_rpc_pwd

rpcallowip=*

-txindex
Maintain a full transaction index, used by the getrawtransaction rpc
call (default: 0)

-rpcpassword=
Password for JSON-RPC connections

-rpcuser=
Username for JSON-RPC connections

Run following command to run the daemon in test node. This will download the data which is around 29gb at the time of writing this blog.

bitcoin-core.daemon -txindex -rpcuser=your_rpc_user -rpcpassword=your_rpc_pwd

This should now start the daemon and will check if the data is available, if not this should start download the blocks.

First it wll pre-Synchronize the block headers and then start Synchronizing headers. At the time of writing this blog there are around 2428000 blocks in test node.

Once synchronizing is complete it should start downloading and indexing blocks-

2023-07-23T15:14:46Z UpdateTip: new best=0000000000002f4ee789f0bd19066bccd78172ca71995505996fbff1a3341eac height=271984 version=0x00000002 log2_work=60.719797 tx=2107245 date=’2014-08-05T09:37:28Z’ progress=0.031835 cache=337.4MiB(2518207txo)

Here the height is the block it has synchronised and the progress. When the progress is near to 1 it will come to completion of synchronising the node.

In the above example 0000000000002f4ee789f0bd19066bccd78172ca71995505996fbff1a3341eac is a block hash

progress when near to 1 means it about to complete synchronising all blocks.

A new folder called testnet3 will be created in .bitcoin folder – This should be in user folder and not root folder.

For me it took less than 2 hours to sync all blocks.

2023-07-23T16:55:23Z UpdateTip: new best=0000000000000022020dfc2655e4489eb54a8ae306080a47d1fa0be46e0c43a8 height=2443382 version=0x31636000 log2_work=75.416383 tx=66092181 date='2023-07-23T16:40:35Z' progress=0.999999 cache=479.2MiB(3458766txo)
2023-07-23T16:56:04Z New outbound peer connected: version: 70015, blocks=2443382, peer=76 (block-relay-only)
2023-07-23T17:00:42Z Saw new header hash=0000000000001019c41ee044adf1c02d347ed52d875eefeb8e629f0a5baa4a8b height=2443383
2023-07-23T17:00:42Z [net] Saw new cmpctblock header hash=0000000000001019c41ee044adf1c02d347ed52d875eefeb8e629f0a5baa4a8b peer=3
2023-07-23T17:00:42Z UpdateTip: new best=0000000000001019c41ee044adf1c02d347ed52d875eefeb8e629f0a5baa4a8b height=2443383 version=0x29e7a000 log2_work=75.416383 tx=66092225 date='2023-07-23T17:00:37Z' progress=1.000000 cache=479.2MiB(3458790txo)

The last block to sync was 2443382

It also listens to any new block been created on chain- 2443383 which happened after 5 minutes. See highlighted.

Quick check-

Pick the block – 2443383

bitcoin-core.cli -rpcuser=xxxx -rpcpassword=xxxxx getblockhash 2443382

It should print the hash-

0000000000000022020dfc2655e4489eb54a8ae306080a47d1fa0be46e0c43a8

Take this hash and use command to get block

bitcoin-core.cli -rpcuser=xxxxxx -rpcpassword=xxxxx getblock 0000000000000022020dfc2655e4489eb54a8ae306080a47d1fa0be46e0c43a8

Output – should show details of the block along with the transactions- I have trimmed the transactions here due to space.

{
  "hash": "0000000000000022020dfc2655e4489eb54a8ae306080a47d1fa0be46e0c43a8",
  "confirmations": 2,
  "height": 2443382,
  "version": 828596224,
  "versionHex": "31636000",
  "merkleroot": "9e0403fef59a803426851f3c428306c15d81360f665f37cc62549825056c6823",
  "time": 1690130435,
  "mediantime": 1690129060,
  "nonce": 2392034863,
  "bits": "192495f8",
  "difficulty": 117392538.8721802,
  "chainwork": "000000000000000000000000000000000000000000000aad36ccc3b8310b4b65",
  "nTx": 26,
  "previousblockhash": "000000000000000b994cbbfe015d77aaa70140af817b6d28d228da690d1ce4da",
  "nextblockhash": "0000000000001019c41ee044adf1c02d347ed52d875eefeb8e629f0a5baa4a8b",
  "strippedsize": 5511,
  "size": 8258,
  "weight": 24791,
  "tx": [
    "b96a95b85e2ec270b471afded7d49c7db46d5002ac43de0bbcc13a4dd972f763",
    "823f5a59b5c6878ba68f21fdfdc9fe796fc879a471d69fcd0430200d9e5aba9a",
    
  ]
}

GetRawTransactions

bitcoin-core.cli -rpcuser=xxxx -rpcpassword=xxxxx getrawtransaction b96a95b85e2ec270b471afded7d49c7db46d5002ac43de0bbcc13a4dd972f763

Output-

010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff1e0376482519444d47426c6f636b636861696e309e3c095f01000000000000ffffffff02b29a270000000000160014b23716e183ba0949c55d6cac21a3e94176eed1120000000000000000266a24aa21a9eddcc8960d06c43b2eaab1e03370081155bac04c26ea7282b8dffaf7c2c452d2220120000000000000000000000000000000000000000000000000000000000000000000000000

This confirms that the blocks are indexed as the getrawtransaction looks for node and not your own wallet transaction.

How to get transaction details will put that in another blog.

Hope this helps to configure full test node on your system.

Performance

To run the daemon blockonly option – 

bitcoind -daemon -blocksonly

.By default, bitcoind relays transactions while you’re syncing and using -blocksonly turns that off. It probably won’t make a huge difference but should save you some bandwidth. 

Increase dbcache

-dbcache= The default for this is 450. If you have 8GB of RAM, you could set this to 4096

Solidity deployment error – ContractNotFound: No contract deployed at address

At time when the Ganache tool is re-opened all the Transactions and Constracts are reset. Whilst deploying contract you might see the error –

ContractNotFound: No contract deployed at {address}

PS C:\Projects\Blockchain\Solidity\brownie_fundme> brownie run .\scripts\deploy.py --network ganache-local
INFO: Could not find files for the given pattern(s).
Brownie v1.19.0 - Python development framework for Ethereum

BrownieFundmeProject is the active project.
  File "C:\Users\sandeep\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\_cli\__main__.py", line 64, in main
    importlib.import_module(f"brownie._cli.{cmd}").main()
  File "C:\Users\sandeep\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\_cli\run.py", line 45, in main
    network.connect(CONFIG.argv["network"])
  File "C:\Users\sandeep\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\network\main.py", line 55, in connect
    p._load_deployments()
  File "C:\Users\sandeep\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\project\main.py", line 370, in _load_deployments
    contract = ProjectContract(self, build, build_json.stem)
  File "C:\Users\sandeep\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\network\contract.py", line 1305, in __init__
    _DeployedContractBase.__init__(self, address, owner, tx)
  File "C:\Users\sandeep\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\network\contract.py", line 708, in __init__
    raise ContractNotFound(f"No contract deployed at {address}")
ContractNotFound: No contract deployed at 0x7465E5ca8aFeFba39eFD83bd056ACAafa3d16646

Solution-

Delete all the files and folders in Deployment folder as closing the Ganache tool will reset contracts etc. the deployment folder has references to old contract.

Reference-

https://stackoverflow.com/questions/68460396/contractnotfound-no-contract-deployed-at

Add new network in Ganache using brownie for Ethereum Smart Contract local development

This should show the list of networks available in Brownie.

brownie networks list

In the Ethereum (persistent network) there is no Ganache(local) network

Add a network to Ethereum

brownie networks add Ethereum ganache-local host=http://127.0.0.1:7545 chainid=1337

Name of the network- ganache-local

host- where ganache endpoint is listening i.e. RPC Server

chainid – for ganache it is 1337

Output

Install Ganache for Solidity development

Ganache is the development tool used to run local blockchain for Ethereum development.

Ganache can be used to deploy the contract to local Blockchain. Its a simutated environemnt like Javascript VM when developing on Remix. It helps spin up a local Blockchain.

Ganache UI

Install the Ganache from following location-

https://trufflesuite.com/ganache/

Click the QUICKSTART to get started with Ethereum. By default Ethereum is selected. Ganache can also be used for Corda development

The next screen shows the local Blockchain with the Accounts having 100 ETH and ready to receive the contracts and transactions.

Options in Ganache in later post.

Ganache CLI-

Similar to Ganache UI the local Blockchain node can be setup using CLI.

Install nodejs – https://nodejs.org/en/download/

Check the version of node js

node -v

Install yarn

npm install --global yarn

Install Ganache CLI

yarn global add ganache-cli

Verify installation by checking the version

ganache-cli --version
Ganache CLI v6.12.2 (ganache-core: 2.13.2)

Use following command to see the Accounts, Transactions, Contracts etc in command line same as UI.

ganache-cli --deterministic

For more CLI options see –

https://www.npmjs.com/package/ganache-cli

Start deploying Contracts, signing and sending transactions to the local Blockchain.

To use Blockchain as a service use-

https://infura.io/

https://www.alchemy.com/

Blockchain Concepts

Advantages of Blockchain-

  • Decentralised – Having no single point of authority
  • Transperancy and Flexibility
  • Speed and Effeciency
  • Security and Immutability
  • Removal of counterparty risk
  • Trust minimised agreements
  • Hybrid smart conrtract with Chain Link (Oracle)

Terms and Abbrevations used in Blockchain-

DAO’s – Decentralised Autonomous Organization’s

Testnet – are free and for testing smart contracts

Mainnet – cost money and are considered “live”

Faucet – is and application that gives us free test token, like free test Rinkeby Ethereum

Block Explorer – an application that allows us to “view” transactions that happen on a blockchain.

Gas – is a unit of computational measure. The more computation a transaction uses the more “gas” you have to pay for.

Every transaction that happens on-chain pays a “gas fee” to node operators.

The amount of “gas” used and how much you pay depends on how “computationally expensive” your transaction is.

Sending ETH to 1 address would be “cheaper” than sending ETH to 1,000 addresses.

Gwei (giga-wei) – denomination or a small unit of Ether 1 Ether is 1 billion Gwei. It is used to measure cost of transaction i.e. used in the Ethereum network to but and sell goods and services.

Gas – Measure of computation use

Gas Price – How much it costs per unit of gas.

Gas Limit – Max amount of gas in a transaction

Transaction Fee – Gas used X Gas Price i.e. 21,000 gas @ 1GWEI per gas =21,000 GWEI

Gas Price of Ehtereum fluctuates based on the demand of the blockchain. More perople using or want to make transactions, the higher the gas price and therefore the higher the transaction fees.

Gnesis Block – First block in a blockchain

Hash – Unique fixed length string to identify a piece of data

Hash Algorithm – A function or algorithm that computes data into a unique hash.

Mining – The precess of finding the “solution” to the blockchain “problem”. Node get paid for mining blocks.

Block – A list of transactions mined together

Nonce – A “number used once” to find the “solution” to the blockchain problem. It’s also used to define the transaction number for an account/address.

Public Key – Is derived from your private key. Anyone can “see” it, and user it, and user it to verify that a transaction came from you.

Private key – Only know to the keyholder, its used to “sign” transactions.

Elliptic Curve Digital Signature Algorithm (ECDSA) – generates public key using private key.

Signing Transactions – A “one way” process. Someone with a private key signs a transaction by their private key being hashed with their transaction data. Anyone can then verify this new transaction hash with your public key.

Node: Single instance in a decentralized network. Anyone can join the network. Blockchains are resilient. Blockchain nodes keep lists of the transactions that occur. They are immutable- nothing can corrupt them.

Consensus – is the mechanism used to agree on the state of a blockchain.

Broken into 2 :-

— Chain Selection

Sybil Resistance – Proof of work. Block Author, defends on fake blockchains

— — PoW – Minners. Uses lot of electricity and is hence costly.

-Transaction Fees and Block Reward.- compete each other to find the answer to the problems. Whoever finds first get the transaction fees.

Sybil Attack – creates fake accounts to influence the network

51% attack

Longest Chain Rule

– — PoS — Validators – nodes put up collateral as a sybil resistance mechanism. Uses less energy. Slightly less decentralised.

ABI– ApplicationBinary Interface- tells Solidity how it can interact with another contract. What functions can be called from the contract. Interfaces compile down to ABI.