Tutorials – Crypto Investing Insider https://cryptoinvestinginsider.com/blog Bitcoin & Cryptocurrency Investing Tue, 04 Jan 2022 01:12:34 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.7 Writing a Smart Contract that takes and gives Ether on Remix [PT1] https://cryptoinvestinginsider.com/blog/writing-a-smart-contract-that-takes-and-gives-ether-on-remix-pt1/?utm_source=rss&utm_medium=rss&utm_campaign=writing-a-smart-contract-that-takes-and-gives-ether-on-remix-pt1 Tue, 04 Jan 2022 01:12:34 +0000 https://cryptoinvestinginsider.com/blog/writing-a-smart-contract-that-takes-and-gives-ether-on-remix-pt1/ Project Parameters: Use a Crypto Oracle to get the Price of Ethereum in US Dollars Create functions that allow for a user to deposit 500 dollar minimum of Ether to our Contract Create functions that allow for the user to withdraw money from the function Write the original contract in Remix, then transition the project to a truffle project, and write tests migrations, and deploy it to a Testnet from VE Ok that’s pretty general but this is way different than a puny state change let’s go: Thinking out loud let’s start with parameter number one, what will we need? For starters we’ll need to use

The post Writing a Smart Contract that takes and gives Ether on Remix [PT1] appeared first on Crypto Investing Insider.

]]>

Project Parameters:

  1. Use a Crypto Oracle to get the Price of Ethereum in US Dollars
  2. Create functions that allow for a user to deposit 500 dollar minimum of Ether to our Contract
  3. Create functions that allow for the user to withdraw money from the function
  4. Write the original contract in Remix, then transition the project to a truffle project, and write tests migrations, and deploy it to a Testnet from VE

Ok that’s pretty general but this is way different than a puny state change let’s go:

Thinking out loud let’s start with parameter number one, what will we need?

  1. For starters we’ll need to use a crypto oracle, let’s use chainlink
  2. We’ll have to figure out how to calculate the price of Ethereum based on the information in the oracle
  3. Create a payable function that allows the user to deposit a given number of ether and hold it.

Let’s start with implementing the price-getting functionality. Let’s start with the Chainlink documentation on getting the latest price.

If you want to implement the get price functionality in your contract you’re first going to have to import the contract itself. The top of your contract should look like the following

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

What the import statement is doing is that it’s actually referencing the chainlink Github and getting the contract that will allow us to fetch the price.

Now onto our actual contract for now we will be working in remix and move it over to a truffle project. So let’s start whipping up the function to get the price. I’ll explain it line by line below.

contract getPaid {
address payable public owner;
address[] public funders;
constructor() {
owner = payable(msg.sender);
function getThePrice() public view returns (uint256) {
//note that the contract address used is the ETH / USD price from the Kovan TestNet
AggregatorV3Interface priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);
(,int256 price,,,) = priceFeed.latestRoundData();
return uint256(price);
}
}

A little note on the variables and the constructor:

  1. the first variable is a null variable that will then be set to the address of whatever person is interacting with the contract.
  2. Then the funders array is an array that only stores addresses in it that will be used when we need to implement withdraw functionality.
  3. If you’re using V8 Compiler than don’t forget to make the owner variable payable because in version 8 msg.sender isn’t automatically payable

Alright, so this is a powerful little function that fetches the price for us every time we call it once it’s deployed:

  1. The Function declaration line declares the function name as well as the type of the function, it’s public meaning it can be called by anybody, it doesn’t change state so it’s a view function, and lastly, it returns the data type uint256 [Unsigned integer 256 bits].
  2. Then the priceFeed variable is declared and you see it’s of the type AggregatorV3Interface, The Fuck? Well, you can actually declare new Objects from imported interfaces in our case because if you look at the solidity file here you see the file starts with Interface. TF is an interface? Think of it as a contract with pre-loaded half-baked functions, half-baked in the sense that you have to tell solidity explicitly how you want it to interact with those functions.
  3. The PriceFeed variable is set equal to an instance of the interface that points to a contract present on the Kovan Test Net that monitors the pair ETH / USD. [Do you see what I meant by half-baked? we had to tell the interface WHAT contract address to interact with]
  4. Then we have this weird piece of code that starts with a parenthesis a comma followed by the data type int256 price and 3 more commas. So if you go to the contract and go to the bottom and look at the function ‘latestRoundData’ you see that the function has 5 return values, and all of them have various information like RoundID when it was updated, and other things but for our cases, we just want the price. You may be asking Sonny why can’t we just set priceFeed equal to int256 price. You would be able to do that if the function only returned one value, but since it returns 5 we need the commas along with the value that we’re returning to add to 5. Since we don’t care to return them we don’t need to fill them out we just need the commas so it knows that we want the price.
  5. then we type coerce the value to a 256-bit unsigned integer and return it. Now if you deploy it on Kovan or whatever testnet you’re using you will see a number that’s way longer than what you anticipated. If you go to the chainlink documentation for each contract address for each pair has a number of decimals that it says it returns so in our case it returns 8 decimal points so if you count 8 figures to the right you get the price in USDs.

Now that we’ve created the price fetching function we can now use that to enforce a minimum deposit value for our smart contract, let’s choose 100 USD so anything less than that will be rejected by our contract. But we’re going to need a second helper function that will convert the price given into Actual dollar-denominated terms

  1. Let’s think about this first before where I said things are denominated to 8 decimal places so if we divide by 10 ^ 8 we should get it to the decimal in the right place where we have a dollar conversion. Let’s code this up
function ConvertPriceToUSD() public view returns (uint256){
uint256 currPrice = getThePrice();
return  (currPrice / 10 ** 8);
//this should move the decimal place enough to get a denomination of ETH in dollar terms
}

Now that we have a way to get the current price is USDs which we can use later to compare the amount of deposited ETH in the funding function below. Also make sure to declare these two values at th:

function deposit() public payable {
uint256 minimumAmt = 100 * 10  ** 18;
require(msg.value >= minimumAmt, "Deposit more fool");
addressToDollarAmt[msg.sender] += msg.value;
funders.push(msg.sender);
}

Alright let’s break down what this function does line by line:

  1. So on line one you see a new keyword and that is payable, that’s our way of telling the Solidity compiler that this function deals with the exchange of money in some capacity.
  2. We then declare a function bound variable that sets a minimum threshold to be tested in the line below, we multiply it by 10 ^ 18 to put it in terms of WEI
  3. We then have a require statement below that says 100 wei is the minimum threshold for the contract, and if they deposit less than that they get an error message.
  4. Then this address gets pushed to the funders array.

Awesome so we’ve implemented deposit functionality for multiple users, but what if our users wanted to withdraw money from the contract, and how do we make sure that ONLY they can withdraw the money that THEY put in, and not anyone else’s ETH?

We’re going to need a few things the first thing is a modifier and the second is the actual withdraw function itself:

modifier onlyOwner {
require(msg.sender == owner);
_;
}
function withdraw() public payable onlyOwner {
payable(msg.sender).transfer(address(this).balance);
for (uint256 funderI=0; funderI < funders.length; funderI++) {
address withdrawlAddy = funders[funderI];
addressToDollarAmt[withdrawlAddy] = 0;
}
funders = new address[](0);
}
  1. Firstly we start with our modifier which is simply just an extra required parameter we can use for our withdrawal function. Don’t miss the “_” so that an exception is thrown instead of you’re contract breaking.
  2. Then as you see on the declaration line we use the modifier only owner, then as you go to the second line we make the msg.sender variable of type variable and then we call the transfer method to transfer the balance of the contract back to the address interacting with the contract.
  3. Don’t forget we also have to update the state of the array to ensure the security of our contract. So we start a loop to loop over the funders array and we set all the values in the array to 0 [so only the array containing the address of the person who’s interacting with it], and then starts a new funders array and sets all the values to 0 in that new array.

Now that you’ve finished the contract it is now time to move out of kushy sandbox that is remix and port it over to truffle. If you have any unresolved bugs check this GitHub Repo.

Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing

Also Read


Writing a Smart Contract that takes and gives Ether on Remix [PT1] was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.

The post Writing a Smart Contract that takes and gives Ether on Remix [PT1] appeared first on Crypto Investing Insider.

]]>
Code and Deploy your First Ethereum Smart Contract using Solidity, Truffle and Ganache https://cryptoinvestinginsider.com/blog/code-and-deploy-your-first-ethereum-smart-contract-using-solidity-truffle-and-ganache/?utm_source=rss&utm_medium=rss&utm_campaign=code-and-deploy-your-first-ethereum-smart-contract-using-solidity-truffle-and-ganache Wed, 18 Aug 2021 01:04:39 +0000 https://cryptoinvestinginsider.com/blog/code-and-deploy-your-first-ethereum-smart-contract-using-solidity-truffle-and-ganache/ source: ethereum.org Code and Deploy your First Ethereum Smart contract using Solidity, Truffle and Ganache With the advent of Bitcoin in 2009, the world witnessed a transformation like none before. The first truly decentralized digital currency was born and would begin a revolution against the financial system as we knew it. But most importantly, the technology behind Bitcoin, called Blockchain attracted great attention. In 2013, Vitalik Buterin published the whitepaper for Ethereum and the project was launched in 2015. It was a community-driven, open-source project and was a major leap in unleashing the potential of blockchain technology. Ethereum is a blockchain

The post Code and Deploy your First Ethereum Smart Contract using Solidity, Truffle and Ganache appeared first on Crypto Investing Insider.

]]>
source: ethereum.org

Code and Deploy your First Ethereum Smart contract using Solidity, Truffle and Ganache

With the advent of Bitcoin in 2009, the world witnessed a transformation like none before. The first truly decentralized digital currency was born and would begin a revolution against the financial system as we knew it. But most importantly, the technology behind Bitcoin, called Blockchain attracted great attention. In 2013, Vitalik Buterin published the whitepaper for Ethereum and the project was launched in 2015. It was a community-driven, open-source project and was a major leap in unleashing the potential of blockchain technology. Ethereum is a blockchain that is designed to support Decentralized applications and Smart contracts, which are essentially a set of agreements that are enforced by the blockchain.

Ethereum smart contracts are written in a programming language called Solidity. It is a Turing-complete statically typed language which is compiled to bytecode that runs on the Ethereum Virtual Machine (EVM). In this tutorial, I shall walk you through the steps involved in coding and deploying a simple counter Ethereum smart contract.

Step 1 – Installing Requirements

Install Node JS (use LTS).

Note: If you’re using Windows, make sure Node and npm have been added to PATH.

We’ll need to install Truffle and Ganache CLI using npm. Open a new terminal window and run the following commands-

$ npm install -g truffle
$ npm install -g ganache-cli

That’s it! Now we can get started with coding our smart contract.

Step 2 – Writing the Smart contract

First let’s create a new truffle project with the name ‘counter’.

$ truffle init counter
$ cd counter

In the contracts/ directory, create a new contract by the name Counter.sol and open it up in a code editor of your choice.

The first line of the contract would specify the supported version of the Solidity compiler, in this case, any version higher than 0.5.0 would be supported.

pragma solidity >=0.5.0;

Now specify a new contract ‘Counter’

contract Counter {
}

with a state variable ‘count’ which contains the current count,

uint count;

which defines a new variable of unsigned integer type and since we haven’t initialised count, it will have a value of 0 by default.

Let’s create a function to increment the count.

function increment() public {
count++;
}

And a function which returns the current value of count, we can specify it as a view function, which means the function only performs a read operation but does not modify the state.

function showCount() public view returns(uint) {
return count;
}

That’s it! The final contract would look like this-

pragma solidity >=0.5.0;
contract Counter {
uint count;
   function increment() public {
count++;
}

function showCount() public view returns(uint) {
return count;
}
}

Now let’s compile the Smart contract, open a terminal and run the command-

$ truffle compile

Hopefully, the smart contract would have compiled successfully without any errors. You might have noticed that a new directory build/ has been created in your repo. It contains the Application Binary Interfaces or ABIs of the smart contracts.

Step 3 – Deploying the Smart contract

Note: There are public test networks available out there which can be used to deploy the contract but for this tutorial we shall make use of a personal blockchain to keep things simple.

Before deploying, first we’ll need to modify the Truffle configuration. Open the truffle-config.js file of the repo and replace it as follows –

module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 8545,
network_id: "*"
},
},
compilers: {
solc: {
optimizer: {
enabled: true,
runs: 200
}
}
}
}

Next, in the migrations/ directory, create a new file named 2_deploy_contracts.js with the following code.

const Counter = artifacts.require("Counter");
module.exports = function(deployer) {
deployer.deploy(Counter);
};

To spin up a personal blockchain on your computer, we shall make use of Ganache. We can use it to deploy and test our smart contract. Open up a separate terminal and run –

$ ganache-cli

You can see that it has got a local blockchain running, with 10 accounts, each having 100 (test) Ether.

All right! Now its finally time to deploy the contract. Go back to the other terminal and run –

$ truffle migrate

And you would have obtained this if the contract was deployed successfully.

To interact with the deployed contract, let’s open up Truffle console and create an instance.

$ truffle console
> counter = await Counter.deployed()

Check the current value of the count variable,

> count = await counter.showCount()
> count.toString()

which will generate an output ‘0’. Now lets call the increment() function and check the new value of count.

> counter.increment()
> count = await counter.showCount()
> count.toString()

And voila! count has been successfully incremented. You can try calling the increment() function multiple times and subsequently check the value of count.

That brings us to the end of this tutorial, in which you’ve learned to code, deploy and interact with a simple counter Ethereum smart contract.

Hope you found this to be helpful! Let me know your doubts and feedback in the comments.

Also, Read

How to write a Smart contract using SmartPy?


Code and Deploy your First Ethereum Smart Contract using Solidity, Truffle and Ganache was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.

The post Code and Deploy your First Ethereum Smart Contract using Solidity, Truffle and Ganache appeared first on Crypto Investing Insider.

]]>
Terminal.co + Next.js https://cryptoinvestinginsider.com/blog/terminal-co-next-js/?utm_source=rss&utm_medium=rss&utm_campaign=terminal-co-next-js Mon, 16 Mar 2020 01:06:11 +0000 https://cryptoinvestinginsider.com/blog/terminal-co-next-js/ Deploy a Nextjs App using Terminal.co and IPFS Overview We’ll create a Next.js app using and deploy it with Terminal.co. This whole process should take 10 minutes. Tools: Terminal.co account GitHub account node.js/npm Step 1: Set Up a Repo on Github Create an empty repository and clone it. Create a Next.js app using: $ mkdir nextjs && cd nextjs$ npm init --y$ npm install next react react-dom Open package.json and add in the following scripts "scripts": { "dev": "next", "build": "next build", "start": "next start", "export": "next export" } Create a next.config.js file in the root directory module.exports = { exportTrailingSlash: true, exportPathMap: function() {

The post Terminal.co + Next.js appeared first on Crypto Investing Insider.

]]>

Deploy a Nextjs App using Terminal.co and IPFS

Overview

We’ll create a Next.js app using and deploy it with Terminal.co. This whole process should take 10 minutes.

Tools:

  • Terminal.co account
  • GitHub account
  • node.js/npm

Step 1: Set Up a Repo on Github

Create an empty repository and clone it.

Create a Next.js app using:

$ mkdir nextjs && cd nextjs
$ npm init --y
$ npm install next react react-dom

Open package.json and add in the following scripts

"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"export": "next export"
}

Create a next.config.js file in the root directory

module.exports = {
exportTrailingSlash: true,
exportPathMap: function() {
return {
'/': { page: '/' }
};
}
};

Let’s create some pages:

Create a folder called pages

Inside pages, create index.js

// index.js
import Link from "next/link";
export default function Index() {
return (

Index



About


);
}

and about.js

// about.js
export default function About() {
return (

About



);
}

It should look something like this

To test, run npm run dev and visit localhost:3000

git add, commit, push

https://github.com/Terminal-Systems-Example/nextjs

Step 2: Set Up Terminal.co

Sign into: https://sites.terminal.co/

Sign in with Github

Add New Site

Connect with Github.

Pick your Next.js repository.

To create a new site:

Build command: npm install && npm run build && npm run export

Publish directory: out

Deploy Site

Once complete, view your website.

You can view the website using the provided domain name.

https://.tmnl.co

Or verify with the CID.

https://ipfs.io/ipfs/

Step 3: Updates

Terminal will automatically redeploy your website whenever you make changes to GitHub. Make sure to provide the domain name will remain the same and will point to the new CID. This enables you to build fast modern websites hosted on IPFS.


Terminal.co + Next.js was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.

The post Terminal.co + Next.js appeared first on Crypto Investing Insider.

]]>
Create Blockchain in Haskell https://cryptoinvestinginsider.com/blog/create-blockchain-in-haskell/?utm_source=rss&utm_medium=rss&utm_campaign=create-blockchain-in-haskell Thu, 17 May 2018 12:05:18 +0000 https://cryptoinvestinginsider.com/blog/create-blockchain-in-haskell/ Rolling your Own Blockchain in Haskell source Attribution — This is republished work of Michael Burge’s blog post Rolling your Own Blockchain in Haskell Bitcoin and Ethereum provide a decentralized means of handling money, contracts, and ownership tokens. From a technical perspective, they have a lot of moving parts and provide a good way to demo a programming language. This article will develop a simple blockchain-like data structure, to demonstrate these in Haskell: Writing a binary serializer and deserializer Using cryptographic primitives to calculate hashes Automatically adjusting the difficulty of a miner in response to computation time. We’ll name it Haskoin. Note that it won’t

The post Create Blockchain in Haskell appeared first on Crypto Investing Insider.

]]>

Rolling your Own Blockchain in Haskell

source

Attribution — This is republished work of Michael Burge’s blog post
Rolling your Own Blockchain in Haskell

Bitcoin and Ethereum provide a decentralized means of handling money, contracts, and ownership tokens. From a technical perspective, they have a lot of moving parts and provide a good way to demo a programming language.

This article will develop a simple blockchain-like data structure, to demonstrate these in Haskell:

  • Writing a binary serializer and deserializer
  • Using cryptographic primitives to calculate hashes
  • Automatically adjusting the difficulty of a miner in response to computation time.

We’ll name it Haskoin. Note that it won’t have any networking or wallet security until a future article.

What is a Blockchain?

The first step when writing any software application is always to figure out your data structures. This is true whether it’s Haskell, Perl, C, or SQL. We’ll put the major types and typeclass instances in their own module:

{-# LANGUAGE GeneralizedNewtypeDeriving, NoImplicitPrelude, DeriveTraversable, DeriveDataTypeable, StandaloneDeriving, TypeSynonymInstances, FlexibleInstances #-}

module Haskoin.Types where

import Protolude
import Crypto.Hash

import Control.Comonad.Cofree
import Data.Data
import qualified Data.Vector as V

newtype Account = Account Integer deriving (Eq, Show, Num)

data Transaction = Transaction {
_from :: Account,
_to :: Account,
_amount :: Integer
} deriving (Eq, Show)

newtype BlockF a = Block (V.Vector a) deriving (Eq, Show, Foldable, Traversable, Functor, Monoid)
type Block = BlockF Transaction

type HaskoinHash = Digest SHA1

data BlockHeader = BlockHeader {
_miner :: Account,
_parentHash :: HaskoinHash
} deriving (Eq, Show)

data MerkleF a = Genesis
| Node BlockHeader a
deriving (Eq, Show, Functor, Traversable, Foldable)

type Blockchain = Cofree MerkleF Block

MerkleF is a higher-order Merkle tree type that adds a layer onto some other type. The Cofree MerkleF Block does two things: It recursively applies MerkleF to produce a type for all depths of Merkle trees, and it attaches an annotation of type Block to each node in the tree.

When using Cofree, anno :< xf will construct one of these annotated values.

It will be more useful to look at an “inverted” tree where each node knows its parent, rather than one where each node knows its children. If each node knew its children, adding a single new block to the end would require changing every node in the tree. So MerkleFproduces a chain, not a tree.

Protolude is a replacement Prelude that I’ve been using recently in moderately-sized projects. Prelude has a lot of backwards-compatibility concerns, so a lot of people shut it off with the NoImplicitPrelude language extension and import a custom one.

Why do we choose this weird MerkleF type over the simpler one below?

newtype Block = Block (V.Vector Transaction)
data Blockchain = Genesis Block
| Node Block BlockHeader Blockchain

The main reason is to get those Functor, Traversable, and Foldable instances, because we can use them to work with our Merkle tree without having to write any code. For example, given a blockchain

import qualified Data.Vector as V

let genesis_block = Block (V.fromList [])
let block1 = Block (V.fromList [Transaction 0 1 1000])
let genesis_chain = genesis_block :< Genesis
let chain1 = block1 :< Node (BlockHeader { _miner = 0, _parentHash = undefined }) genesis_chain
let chain2 = block1 :< Node (BlockHeader { _miner = 0, _parentHash = undefined }) chain1

, here’s how you can get all of its transactions:

let txns = toList $ mconcat $ toList chain2
-- [Transaction {_from = Account 0, _to = Account 1, _amount = 1000},Transaction {_from = Account 0, _to = Account 1, _amount = 1000}]
let totalVolume = sum $ map _amount txns
-- 2000

I tested the above using stack ghci to enter an interactive prompt.

Real blockchains have a lot of useful things in the header, such as timestamps or nonce values. We can add them to BlockHeader as we need them.

Constructing Chains

A bunch of abstract types that are awkward to use aren’t very useful by themselves. We need a way to mine new blocks to do anything interesting. In other words, we want to define mineOn and makeGenesis:

module Haskoin.Mining where

type TransactionPool = IO [Transaction]

mineOn :: TransactionPool -> Account -> Blockchain -> IO Blockchain
mineOn pendingTransactions minerAccount root = undefined

makeGenesis :: IO Blockchain
makeGenesis = undefined

The genesis block is pretty easy, since it doesn’t have a header:

makeGenesis = return $ Block (V.fromList []:< Genesis

We can write mineOn without any difficulty, transaction limiting, or security pretty easily if we knew how to calculate a parent node’s hash:

mineOn :: TransactionPool -> Account -> Blockchain -> IO Blockchain
mineOn pendingTransactions minerAccount parent = do
ts <- pendingTransactions
let block = Block (V.fromList ts)
let header = BlockHeader {
_miner = minerAccount,
_parentHash = hash parent
}
return $ block :< Node header parent

hash :: Blockchain -> HaskoinHash
hash = undefined

Crypto.Hash has plenty of ways to hash something, and we’ve chosen type HaskoinHash = Digest SHA1 earlier. But in order to use it, we need some actual bytes to hash. That means we need a way to serialize and deserialize a Blockchain. A common library to do that is binary, which provides a Binary typeclass that we’ll implement for our types.

It’s not difficult to write instances by hand, but one of the advantages of using weird recursive types is that the compiler can generate Binary instances for us. Here’s complete code to serialize and deserialize every type we need:

{-# LANGUAGE StandaloneDeriving, TypeSynonymInstances, FlexibleInstances, UndecidableInstances, DeriveGeneric, GeneralizedNewtypeDeriving #-}

module Haskoin.Serialization where

import Haskoin.Types
import Control.Comonad.Cofree
import Crypto.Hash
import Data.Binary
import Data.Binary.Get
import Data.ByteArray
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.Vector.Binary
import GHC.Generics

instance (Binary (f (Cofree f a)), Binary a) => Binary (Cofree f a) where
instance (Binary a) => Binary (MerkleF a) where
instance Binary BlockHeader where
instance Binary Transaction where
deriving instance Binary Account
deriving instance Binary Block

deriving instance Generic (Cofree f a)
deriving instance Generic (MerkleF a)
deriving instance Generic BlockHeader
deriving instance Generic Transaction
instance Binary HaskoinHash where
get = do
mDigest <- digestFromByteString <$> (get :: Get BS.ByteString)
case mDigest of
Nothing -> fail "Not a valid digest"
Just digest -> return digest
put digest = put $ (convert digest :: BS.ByteString)

deserialize :: BSL.ByteString -> Blockchain
deserialize = decode

serialize :: Blockchain -> BSL.ByteString
serialize = encode

I only included deserialize and serialize to make it clearer what the end result of this module is. Let’s drop them in favor of decode and encode from Data.Binary.

Generic is a way of converting a value into a very lightweight “syntax tree” that can be used by serializers(JSON, XML, Binary, etc.) and many other typeclasses to provide useful default definitions. The Haskell wiki has a good overview. binary uses these Genericinstances to define serializers that work on just about anything.

We had to hand-write a Binary instance for HaskoinHash because Digest SHA1from the Crypto.Hash library didn’t provide it or a Generic instance. That’s okay – digests are pretty much bytestrings anyways, so it was only a few lines.

Here’s how to use them to implement mineOn:

import Crypto.Hash(hashlazy)

mineOn :: TransactionPool -> Account -> Blockchain -> IO Blockchain
mineOn pendingTransactions minerAccount parent = do
ts <- pendingTransactions
let block = Block (V.fromList ts)
let header = BlockHeader {
_miner = minerAccount,
_parentHash = hashlazy $ encode parent
}
return $ block :< Node header parent

And here’s how to test that this actually works:

testMining :: IO Blockchain
testMining = do
let txnPool = return []
chain <- makeGenesis
chain <- mineOn txnPool 0 chain
chain <- mineOn txnPool 0 chain
chain <- mineOn txnPool 0 chain
chain <- mineOn txnPool 0 chain
chain <- mineOn txnPool 0 chain
return chain

-- GHCI
> chain <- testMining
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = efb3febc87c41fffb673a81ed14a6fb4f736df79}) (
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = 2accb557297850656de70bfc3e13ea92a4ddac29}) (
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = f51e30233feb41a228706d1357892d16af69c03b}) (
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = 0072e83ae8e9e22d5711fd832d350f5a279c1c12}) (
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = c259e771b237769cb6bce9a5ab734c576a6da3e1}) (
Block [] :< Genesis)))))
> encode chain
"NULNULNULNULNULNULNULNULSOHNULNULNULNULNULNULNULNULNULNULNULNULDC4239179254188135196US255182s168RS209Jo180247&6223yNULNULNULNULNULNULNULNULSOHNULNULNULNULNULNULNULNULNULNULNULNULDC4*204181W)xPem231v252>DC3234146164221172)NULNULNULNULNULNULNULNULSOHNULNULNULNULNULNULNULNULNULNULNULNULDC4245RS0#?235A162(pmDC3W137-SYN175i192;NULNULNULNULNULNULNULNULSOHNULNULNULNULNULNULNULNULNULNULNULNULDC4NULr232:232233226-WDC1253131-5SIZ'156FSDC2NULNULNULNULNULNULNULNULSOHNULNULNULNULNULNULNULNULNULNULNULNULDC4194Y231q178&7v156182188233165171sLWjm163225NULNULNULNULNULNULNULNULNUL"
> (decode $ encode chain) :: Blockchain
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = efb3febc87c41fffb673a81ed14a6fb4f736df79}) (
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = 2accb557297850656de70bfc3e13ea92a4ddac29}) (
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = f51e30233feb41a228706d1357892d16af69c03b}) (
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = 0072e83ae8e9e22d5711fd832d350f5a279c1c12}) (
Block [] :< Node (BlockHeader {_miner = Account 0, _parentHash = c259e771b237769cb6bce9a5ab734c576a6da3e1}) (
Block [] :< Genesis)))))

If you’re testing serialization code at home, you may prefer to use the base16-bytestring library to hex-encode your ByteStrings:

> import qualified Data.ByteString.Base16.Lazy as BSL
> chain <- testMining
> BSL.encode $ encode chain
00000000000000000100000000000000000000000014efb3febc87c41fffb673a81ed14a6fb4f736df79000000000000000001000000000000000000000000142accb557297850656de70bfc3e13ea92a4ddac2900000000000000000100000000000000000000000014f51e30233feb41a228706d1357892d16af69c03b000000000000000001000000000000000000000000140072e83ae8e9e22d5711fd832d350f5a279c1c1200000000000000000100000000000000000000000014c259e771b237769cb6bce9a5ab734c576a6da3e1000000000000000000

Note that it will probably be a PITA for a C programmer trying to follow our serialization/deserialization code because the byte-wrangling is hidden in a lot of really generic code. If you want to produce a spec for people to use(always a good idea), you’ll probably want to hand-roll your serialization code so it’s self-documenting.

Mining

There are a couple mining-related problems with this so-called blockchain:

  1. People can have negative balances, so people can create a “scapegoat account” that they transfer unlimited amounts of money from.
  2. There is no transaction limiting, so someone could create a huge block and run our miners out of memory.
  3. We always mine empty blocks, so nobody can transfer money.
  4. There is no difficulty, so miners aren’t proving they’ve done any work.

I say that these are all mining problems because the code that miners run is going to deal with them.

#3 we’ll wait for Networking to solve. The rest we can do now.

To solve #1, we need account balances for anyone with a transaction that we’re mining a block for. Let’s go ahead and calculate all possible account balances:

blockReward = 1000

balances :: Blockchain -> M.Map Account Integer
balances bc =
let txns = toList $ mconcat $ toList bc
debits = map (Transaction{ _from = acc, _amount = amount} -> (acc, -amount)) txns
credits = map (Transaction{ _to = acc, _amount = amount} -> (acc, amount)) txns
minings = map (h -> (_minerAccount h, blockReward)) $ headers bc
in M.fromListWith (+) $ debits ++ credits ++ minings

And then once we have a parent blockchain, we know how to filter out the invalid transactions:

validTransactions :: Blockchain -> [Transaction] -> [Transaction]
validTransactions bc txns =
let accounts = balances bc
validTxn txn = case M.lookup (_from txn) accounts of
Nothing -> False
Just balance -> balance >= _amount txn
in filter validTxn txns

To solve #2, I’ll let the current miner choose however many transactions he wants to put in his block. That means I’ll put a constant globalTransactionLimit = 1000 at the top that we’ll use when mining, but we won’t verify past blocks using it.

To solve #4, we need to add a nonce field to our BlockHeader that the miner can increment until he finds a good hash. We’ll make it an arbitrarily-large integer to avoid the scenario that no nonce values yield a sufficiently-difficult hash. And since we want to adjust our difficulty so blocks take roughly the same time to mine, we’ll store a timestamp in the header.

import Data.Time.Clock.POSIX

-- Add new fields
data BlockHeader = BlockHeader {
_miner :: Account,
_parentHash :: HaskoinHash,
_nonce :: Integer,
_minedAt :: POSIXTime
} deriving (Eq, Show)

-- Add serializers for POSIXTime
instance Binary POSIXTime where
get = fromInteger <$> (get :: Get Integer)
put x = put $ (round x :: Integer)

globalTransactionLimit = 1000

mineOn :: TransactionPool -> Account -> Blockchain -> IO Blockchain
mineOn pendingTransactions minerAccount parent = do
ts <- pendingTransactions
ts <- return $ validTransactions parent ts
ts <- return $ take globalTransactionLimit ts
loop ts 0
where
validChain bc = difficulty bc < desiredDifficulty parent
loop ts nonce = do
now <- getPOSIXTime
let header = BlockHeader {
_miner = minerAccount,
_parentHash = hashlazy $ encode parent,
_nonce = nonce,
_minedAt = now
}
block = Block (V.fromList ts)
candidate = block :< Node header parent
if validChain candidate
then return candidate
else loop ts (nonce+1)

difficulty :: Blockchain -> Integer
difficulty = undefined

desiredDifficulty :: BlockChain -> Integer
desiredDifficulty = undefined

We enter loop and keep incrementing the counter and fetching the time until we find a candidate with the right difficulty. The actual difficulty of a Blockchain is just its hash converted to an integer:

import Crypto.Number.Serialize(os2ip)

difficulty :: Blockchain -> Integer
difficulty bc = os2ip $ (hashlazy $ encode bc :: HaskoinHash)

How do we know what the right difficulty is? To start with, we’ll calculate the average time-between-blocks for the last 100 blocks:

numBlocksToCalculateDifficulty = 100

blockTimeAverage :: BlockChain -> NominalDiffTime
blockTimeAverage bc = average $ zipWith (-) times (tail times)
where
times = take numBlocksToCalculateDifficulty $ map _minedAt $ headers bc

headers :: BlockChain -> [BlockHeader]
headers Genesis = []
headers (_ :< Node x next) = x : headers next

average :: (Foldable f, Num a, Fractional a, Eq a) => f a -> a
average xs = sum xs / (if d == 0 then 1 else d) where d = fromIntegral $ length xs

Let’s have a target time of 10 seconds. Suppose blockTimeAverage bc gives 2 seconds, so we want blocks to take 5 times as long: adjustmentFactor = targetTime / blockTimeAverage bc = 5. Which means we want only 1/5 of the originally-accepted blocks to be accepted.

Since hashes are uniformly-distributed, 1/5 of the original hashes are less than originalDifficulty / 5, which will be our new difficulty. That’s what Bitcoin does: difficulty = oldDifficulty * (2 weeks) / (time for past 2015 blocks).

genesisBlockDifficulty = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
targetTime = 10

-- BEWARE: O(n * k), where k = numBlocksToCalculateDifficulty
desiredDifficulty :: Blockchain -> Integer
desiredDifficulty x = round $ loop x
where
loop (_ :< Genesis) = genesisBlockDifficulty
loop x@(_ :< Node _ xs) = oldDifficulty / adjustmentFactor
where
oldDifficulty = loop xs
adjustmentFactor = min 4.0 $ targetTime `safeDiv` blockTimeAverage x

Here are a few recent mining times using these calculations:

> exampleChain <- testMining
> exampleChain <- mineOn (return []) 0 exampleChain -- Repeat a bunch of times
> mapM_ print $ map blockTimeAverage $ chains exampleChain
6.61261425s
6.73220925s
7.97893375s
12.96145975s
10.923974s
9.59857375s
7.1819445s
2.2767425s
3.2307515s
7.215131s
15.98277575s

They hover around 10s because targetTime = 10.

Persistence

We’ll save the blockchain on disk, and give people 3 tools:

  • A tool to mine blocks and create a new chain
  • A tool to list account balances

The first tool is the miner:

{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}

module Haskoin.Cli.Mine where

import Haskoin.Mining
import Haskoin.Serialization
import Haskoin.Types

import Protolude
import System.Environment
import Data.Binary
import qualified Data.ByteString.Lazy as BSL
import System.Directory
import Prelude(read)

defaultChainFile = "main.chain"
defaultAccount = "10"

main :: IO ()
main = do
args <- getArgs
let (filename, accountS) = case args of
[] -> (defaultChainFile, defaultAccount)
[filename] -> (filename, defaultAccount)
[filename, account] -> (filename, account)
_ -> panic "Usage: mine [filename] [account]"
swapFile = filename ++ ".tmp"
txnPool = return []
account = Account $ read accountS
forever $ do
chain <- loadOrCreate filename makeGenesis :: IO Blockchain
newChain <- mineOn txnPool account chain
encodeFile swapFile newChain
copyFile swapFile filename
print "Block mined and saved!"

loadOrCreate :: Binary a => FilePath -> (IO a) -> IO a
loadOrCreate filename init = do
exists <- doesFileExist filename
if exists
then decodeFile filename
else do
x <- init
encodeFile filename x
return x

The second one prints all of the account balances

{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}

module Haskoin.Cli.ListBalances where

import Haskoin.Mining
import Haskoin.Serialization
import Haskoin.Types

import Protolude
import System.Environment
import Data.Binary
import qualified Data.Map as M
import qualified Data.ByteString.Lazy as BSL

defaultChainFile = "main.chain"

main :: IO ()
main = do
args <- getArgs
let (filename) = case args of
[] -> (defaultChainFile)
[filename] -> (filename)
_ -> panic "Usage: list-balances [filename]"
chain <- decodeFile filename :: IO Blockchain
forM_ (M.toAscList $ balances chain) $ (account, balance) -> do
print (account, balance)

Here’s its output:

$ stack exec list-balances
(Account 10,23000)

So I’ve apparently mined 23 blocks just testing stack exec mine.

Conclusion

We developed a simple blockchain data structure. You can browse the repository on Github.

Future Haskoin-related articles may cover

  • Using networking and concurrency primitives to set up a peer-to-peer network.
  • Securing accounts in wallets, so other people can’t transfer money out of your account.
  • Building a ‘blockchain explorer’ website
  • GPU-accelerating our hashing
  • FPGA-accelerating our hashing

Future cryptocurrency-related articles may cover:

  • You may have heard about proof-of-work and proof-of-stake. What about proof-of-proof — where the miners compete to prove novel theorems in an approriate logic?
  • Adding a Turing-complete scripting language
  • Better ways to parse command line options
  • Building a Bitcoin exchange


Create Blockchain in Haskell was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.

The post Create Blockchain in Haskell appeared first on Crypto Investing Insider.

]]>
Part 1: Ethereum Blockchain on IBM Cloud :- Deploying Private Ethereum Blockchain on IBM Cloud… https://cryptoinvestinginsider.com/blog/part-1-ethereum-blockchain-on-ibm-cloud-deploying-private-ethereum-blockchain-on-ibm-cloud/?utm_source=rss&utm_medium=rss&utm_campaign=part-1-ethereum-blockchain-on-ibm-cloud-deploying-private-ethereum-blockchain-on-ibm-cloud Wed, 16 May 2018 12:39:27 +0000 https://cryptoinvestinginsider.com/blog/part-1-ethereum-blockchain-on-ibm-cloud-deploying-private-ethereum-blockchain-on-ibm-cloud/ Part 1: Ethereum Blockchain on IBM Cloud :- Deploying Private Ethereum Blockchain on IBM Cloud Containers What is IBM Cloud ? IBM Cloud is a cloud platform developed by IBM which is based on Cloud Foundry and runs of SoftLayer Infrastructure. It supports various programming languages, Databases, Services, as well as integrated DevOps to build, run, deploy and manage applications on the cloud using IBM Container service. Prerequisites Signup for IBM Cloud free trial https://console.bluemix.net/registration/ Install IBM Cloud cli https://console.bluemix.net/docs/cli/reference/bluemix_cli/get_started.html Install Dockers https://docs.docker.com/engine/installation/ Install and Setup Kubectl https://kubernetes.io/docs/tasks/tools/install-kubectl/ Build your Docker Image Clone my Git repository > git clone https://github.com/SaifRehman/IBMCLOUD-Ethereum-Blockchain.git> cd IBMCLOUD-Ethereum-Blockchain/ Build the Image from

The post Part 1: Ethereum Blockchain on IBM Cloud :- Deploying Private Ethereum Blockchain on IBM Cloud… appeared first on Crypto Investing Insider.

]]>

Part 1: Ethereum Blockchain on IBM Cloud :- Deploying Private Ethereum Blockchain on IBM Cloud Containers

What is IBM Cloud ?

IBM Cloud is a cloud platform developed by IBM which is based on Cloud Foundry and runs of SoftLayer Infrastructure. It supports various programming languages, Databases, Services, as well as integrated DevOps to build, run, deploy and manage applications on the cloud using IBM Container service.

Prerequisites

Signup for IBM Cloud free trial

https://console.bluemix.net/registration/

Install IBM Cloud cli

https://console.bluemix.net/docs/cli/reference/bluemix_cli/get_started.html

Install Dockers

https://docs.docker.com/engine/installation/

Install and Setup Kubectl

https://kubernetes.io/docs/tasks/tools/install-kubectl/

Build your Docker Image

Clone my Git repository

> git clone https://github.com/SaifRehman/IBMCLOUD-Ethereum-Blockchain.git
> cd IBMCLOUD-Ethereum-Blockchain/

Build the Image from the Dockerfile

> docker build -t myimage .
Will take some time to build the image 🙂

Check if you have the image in your system

> docker images

Login to IBM Cloud & Create a new Container

https://console.bluemix.net

IBM Cloud

Create a lite container on IBM Cloud by choosing container service. Do not forget to give your container a name 🙂 Let’s name it “ether”

Create a lite container for free. Wait for for some time it will take some time to deploy
After deploying you will see something like this

Setup your Container

Do not follow along these steps unless your container is fully deployed!

Install container-service bx plugin

> bx plugin install container-service -r Bluemix

Log in to your IBM Cloud account.

> bx login -a https://api.ng.bluemix.net

Set your terminal context to your cluster

> bx cs cluster-config ether
You will see something like this, and configuration will be automatically downloaded

Export environment variables to start using Kubernetes by copy pasting the resulting yellow line of code

> export KUBECONFIG=/Users/saifrehman/.bluemix/plugins/container-service/clusters/ether/kube-config-dal10-ether.yml

Push the image from your machine to IBM Cloud Private Registery

Tag an image to point to this registry. Choose a local image, target namespace, and target repository.

Install the Container Registry plug-in.

> bx plugin install container-registry -r Bluemix

Choose a name for your first namespace, and create that namespace. Use this namespace for the rest of the Quick Start.

bx cr namespace-add

> bx cr namespace-add etherprivate

Log your local Docker daemon into the IBM Cloud Container Registry.

> bx cr login

docker tag registry.ng.bluemix.net//

> docker tag myimage registry.ng.bluemix.net/etherprivate/myimage

docker push registry.ng.bluemix.net//

> docker push registry.ng.bluemix.net/etherprivate/myimage
This will push the image to IBM Cloud Private image registry. This will take some time 🙂

Deploy your Image to Kubernetes Cluster on IBM Cloud

Setup your service.deployment.yml file

Configure your Kubernetes Cluster

Deploy 🙂

> kubectl create -f service-deployment.yml
You can now access your application through the public IP

Test if you can access

curl http://169.47.252.115:30090

Don’t worry if you do not seen any output, it will not return you anything 🙂

Access your Private Ethereum Blockchain running on IBM Container

> geth attach http://169.47.252.115:30090
Cooool. You now have a ethereum blockchain spinning on IBM Cloud

Let’s start mining Ether!

Create and unlock your new account to start mining

> personal.newAccount('password')
> personal.unlockAccount(web3.eth.coinbase, "password", 15000)

Start mining to get enough ether for us to deploy smart contract in our next tutorial 🙂

> miner.start()

Check your Ether Balance

> web3.fromWei(eth.getBalance(eth.coinbase), "ether")

Stop mining

> miner.stop()

Congratulation you have successfully setup your Private Ethereum Blockchain on IBM Cloud!

Next

Working with solidity to deploy your first ethereum smart contract on IBM Cloud and creating Dapp front-end on Angular 4

Click to know more about ethereum


Part 1: Ethereum Blockchain on IBM Cloud :- Deploying Private Ethereum Blockchain on IBM Cloud… was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.

The post Part 1: Ethereum Blockchain on IBM Cloud :- Deploying Private Ethereum Blockchain on IBM Cloud… appeared first on Crypto Investing Insider.

]]>
Building A Simple Blockchain Data Structure With Python https://cryptoinvestinginsider.com/blog/building-a-simple-blockchain-data-structure-with-python/?utm_source=rss&utm_medium=rss&utm_campaign=building-a-simple-blockchain-data-structure-with-python Wed, 16 May 2018 12:39:03 +0000 https://cryptoinvestinginsider.com/blog/building-a-simple-blockchain-data-structure-with-python/ Photo by Mateusz Dach from Pexels Here, I am going to build a simple blockchain data structure which is the foundation of Bitcoin. This data structure only is not enough to build even a simple cryptocurrency. But we have to start somewhere. Before building a blockchain data structure, I have to explain about hashing. Bitcoin uses SHA-256. Here how you can do it in Python: >>> import hashlib>>> hashlib.sha256(b”hello world”).hexdigest()‘b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9’ That is how you do hashing (SHA-256) in Python. But what is actually hash? What does 256 in SHA-256 means actually? Hashing is a process which you turn anything (as long as

The post Building A Simple Blockchain Data Structure With Python appeared first on Crypto Investing Insider.

]]>
Photo by Mateusz Dach from Pexels

Here, I am going to build a simple blockchain data structure which is the foundation of Bitcoin. This data structure only is not enough to build even a simple cryptocurrency. But we have to start somewhere.

Before building a blockchain data structure, I have to explain about hashing. Bitcoin uses SHA-256. Here how you can do it in Python:

>>> import hashlib
>>> hashlib.sha256(b”hello world”).hexdigest()
‘b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9’

That is how you do hashing (SHA-256) in Python. But what is actually hash? What does 256 in SHA-256 means actually?

Hashing is a process which you turn anything (as long as you can represent it as a string) into a fixed 256 bit string. In the previous example, the string “hello world” has a length 11. Actually the length of “hello world” is depended on how you count it. But for simplicity, we just count how many characters. That “hello world” string is turned into a fixed-size string, which is ‘b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9’. Say I hash another string with different length.

>>> import hashlib
>>> hashlib.sha256(b”I am the best president. Ever.”).hexdigest()
‘fba0e4cc233f9df81278130ed748a31a842bce8f911766b661f8a4f7ddff5341’

The string “I am the best president. Ever.” has a different length than “hello world”. But the output has the same length, which is about 64 characters. So any input will be turned into 64 random characters string. Even a string which has a 23 kilometers length will be turned into a 64 random characters string.

This is a hexadecimal string. That’s why it has 64 characters. If you turn it into a bit string, it will have a 256 characters length.

>>> bin(0xb94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9)
‘0b1011100101001101001001111011100110010011010011010011111000001000101001010010111001010010110101111101101001111101101010111111101011000100100001001110111111100011011110100101001110000000111011101001000010001000111101111010110011100010111011111100110111101001’

That is why it is called SHA-256.

Now, there are some properties from hashing which is very important for Bitcoin. The first is called collision free. I mean if you are going to turn anything into a fixed 256 bit string, surely there will be more than 1 input that has the same output. The size of possible inputs is bigger than the size of possible output. Yes, that’s correct. But finding x and y where x is different than y and hash(x) is equal hash(y) is extremely hard (in SHA-256 case; some smart people have found collision in SHA-1).

So there is no apparent relation between the input and the output. Even you change the tiny bit of the input, the output will be totally different. This is the second property.

>>> hashlib.sha256(b”1").hexdigest()
‘6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b’
>>> hashlib.sha256(b”2").hexdigest()
‘d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35’
>>> hashlib.sha256(b”3").hexdigest()
‘4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce’
>>> hashlib.sha256(b”11").hexdigest()
‘4fc82b26aecb47d2868c4efbe3581732a3e7cbcc6c2efb32062c08170a05eeb8’

So the only way to to find different inputs which have the same output, you need to test all combination of characters with different length. “abc”, “maybe a loooooong string”, “17”, etc. It’s totally impractical.

But is there any possibility that when you hash something, the output is already same as hashing of “hello world”? Or just any two different strings but have the same hash? Of course, there is. The question is how minuscule the probability is. There are around 2²⁵⁶ possibilities of the output of SHA-256. How big is 2²⁵⁶? 115792089237316195423570985008687907853269984665640564039457584007913129639936. Or 1.15 e+77. Or roughly 10⁷⁷. If you think that number is big but not very big, I have a bad news for you. The total atom in observable universe (that is the universe that you can see up to 46 billions light years in any direction from your chair) is 10⁷⁸ to 10⁸². https://www.universetoday.com/36302/atoms-in-the-universe/

My computer has Nvidia Geforce 1080 Ti. It has 11.3 teraflops (tera = 10¹²). Flop is floating operation. Hashing is integer operation. So it’s apple to orange. But for simplicity, say hashing is an floating operation as well and requires 3000 operations per hash. So my graphic card can compute 3766666666 hash per second. To find a collision, described in birthday attack, we need only to compute 2¹²⁸ hashes. Say every human on this planet has my graphic card and together we compute the collision attack. It takes:

>>> 2**128 / (7000000000 * 3766666666.6666665)
1.2905778770705631e+19

That number is longer than the age of universe (around 10¹⁷ seconds). https://www.space.com/24054-how-old-is-the-universe.html

To describe the hashing algorithm, it is quite a work. But someday I’ll explain the code behind SHA-256. Now that you can comprehend the vastness of hashing, let’s move on. Blockchain is like a linked list, a data structure known by many computer science students. Let’s create a block. The first block in Bitcoin is called genesis block.

import hashlib, json
block_genesis = {
‘prev_hash’: None,
‘transactions’: [1, 3, 4, 2]
}

The transactions represents the… well, transactions. In Bitcoin, it will be like “Jason pays 2 btc to Mary Sue”, “Kylo Rein pays 10 btc to Yoda”. For simplicity, we just put normal integers.

We serialized the block so it can be hashed.

block_genesis_serialized = json.dumps(block_genesis, sort_keys=True).encode(‘utf-8’)
block_genesis_hash = hashlib.sha256(block_genesis_serialized).hexdigest()

Now we have another block.

block_2 = {
‘prev_hash’: block_genesis_hash,
‘transactions’: [3, 3, 3, 8, 7, 12]
}

We hash the block 2.

block_2_serialized = json.dumps(block_2, sort_keys=True).encode(‘utf-8’)
block_2_hash = hashlib.sha256(block_2_serialized).hexdigest()

We build another block.

block_3 = {
‘prev_hash’: block_2_hash,
‘transactions’: [3, 4, 4, 8, 34]
}

We hash the block 3. This will be the last block, I promise.

block_3_serialized = json.dumps(block_3, sort_keys=True).encode(‘utf-8’)
block_3_hash = hashlib.sha256(block_3_serialized).hexdigest()

To make sure that data has not been tampered, I only need to check the last block’s hash, instead of checking all the data from genesis block to the last block. If it is different, than someone tried to tamper the data.

import hashlib, json
block_genesis = {
‘prev_hash’: None,
‘transactions’: [1, 3, 4, 2]
}
block_2 = {
‘prev_hash’: None,
‘transactions’: [3, 3, 3, 8, 7, 12]
}
block_3 = {
‘prev_hash’: None,
‘transactions’: [3, 4, 4, 8, 34]
}
def hash_blocks(blocks):
prev_hash = None
for block in blocks:
block[‘prev_hash’] = prev_hash
block_serialized = json.dumps(block, sort_keys=True).encode(‘utf-8’)
block_hash = hashlib.sha256(block_serialized).hexdigest()
prev_hash = block_hash
 return prev_hash
print(“Original hash”)
print(hash_blocks([block_genesis, block_2, block_3]))
print(“Tampering the data”)
block_genesis[‘transactions’][0] = 3
print(“After being tampered”)
print(hash_blocks([block_genesis, block_2, block_3]))

The result:

Original hash
45eda4f7a76bf0f92a0acda2ce4752dfbe167473376f766f22d7ec68501cac40
Tampering the data
After being tampered
27d68dae05428be6aa244869196a481f431fca6645dd33c3df7a740afa03b7d9

This is the basic of the blockchain. But this is not enough. How do you decide the next block to be added? You need consensus and proof of work. Then the block structure in Blockchain is much more complicated. We’ll cover that in next articles.

If you like this article, you can fund my campaign on creating Cryptocurrencies and Blockchain Course For Hackers.


Building A Simple Blockchain Data Structure With Python was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.

The post Building A Simple Blockchain Data Structure With Python appeared first on Crypto Investing Insider.

]]>
Cryptocurrency Investing — Why Some Get Scammed While Others Get Rich https://cryptoinvestinginsider.com/blog/cryptocurrency-investing-why-some-get-scammed-while-others-get-rich/?utm_source=rss&utm_medium=rss&utm_campaign=cryptocurrency-investing-why-some-get-scammed-while-others-get-rich https://cryptoinvestinginsider.com/blog/cryptocurrency-investing-why-some-get-scammed-while-others-get-rich/#respond Thu, 05 Apr 2018 20:47:41 +0000 https://cryptoinvestinginsider.com/blog/?p=2510 What makes for a winning crypto investment? Rewind to the beginning of 2017 and hardly anyone could name a cryptocurrency other than bitcoin. Today it seems wherever I go, the first thing people want to talk about is what cryptocurrency am I recommending? Everyone wants to make that big payday blockchain investment while staying clear of the latest crypto-scam. Scams have made headlines since the inception of the internet and with the advent of cryptocurrency, the topic is still trendy. Scams in the cryptocurrency space, both recorded and unrecorded, continues to multiply on a daily basis, with recent updates suggesting

The post Cryptocurrency Investing — Why Some Get Scammed While Others Get Rich appeared first on Crypto Investing Insider.

]]>
What makes for a winning crypto investment?

Rewind to the beginning of 2017 and hardly anyone could name a cryptocurrency other than bitcoin. Today it seems wherever I go, the first thing people want to talk about is what cryptocurrency am I recommending? Everyone wants to make that big payday blockchain investment while staying clear of the latest crypto-scam.

Scams have made headlines since the inception of the internet and with the advent of cryptocurrency, the topic is still trendy. Scams in the cryptocurrency space, both recorded and unrecorded, continues to multiply on a daily basis, with recent updates suggesting that about $9 million is lost daily to cryptocurrency scams.

The most popular types include Ponzi schemes, fraud, phishing, initial coin offering (ICO) scams, hacking, fake application, and even theft. Although this is heartbreaking, it’s believed that individuals who indulge in these distasteful activities, both the investors and the operators of the schemes, are forced to do so by their station and financial status. Cryptocurrency enthusiasts hope that the scams in the industry will be reduced to a minimal level as technology advances rapidly.

However, it’s clear that with the advancement of scams, there’s also the further development of increased sophistication and higher frequency. New strategies to scam investors are devised on a regular basis and the population of individuals who engage in these schemes continues to grow. It’s believed that the scams in the cryptocurrency industry are what has set the government of many nations as well as financial institutions and experts against the notion of digital coins.

In recent times, financial institutions and even search engines and social media platform have taken active steps to reduce or ban transactions and ICO ads from their platform. Financial experts have also dedicated time and resources to educate investors across the globe of the risk involved in putting cash into digital coins. Meanwhile, the number of investment in this virtual currency continues to multiply.

A few financial experts have taken a different stand, stating that investors are not to blame for putting their money into something as uncertain as cryptocurrency investment, rather their impecuniosity should be seen as the culprit.

It’s true that a substantial proportion of the population has close to zero investment opportunities. The heat of this situation can be safely blamed when such individual decides to invest in get-rich-quick schemes in the cryptocurrency space or even partake in such activities. For instance, Ponzi schemes promise to reward its investors with a substantial amount of money within a short period of time, which sounds exciting to individuals who tirelessly search for ways to make ends meet.

It’s believed that the risk in the cryptocurrency space is not half as much as that in the lotto and gambling industry, yet the government legalize it and forbid cryptocurrency transactions. Statistically, it’s estimated that about half of United States adult play the lottery. This a large number and if an average lottery player wages $5 a week, it will amount to $260 annually, which is almost a certain guaranteed loss.lottery

It’s important to state that this figure does not include the money spent betting on illegal gambling schemes such as online poker or sports betting where the figure may be quadrupled. Cryptocurrency, on the other hand, is believed to be a risky exercise that offers no guarantee or consumer protection, but this point can be safely argued otherwise.

A smart and intelligent cryptocurrency investor can convert a meager capital into a substantial sum of money in the digital coins space, but no matter how disciplined a gambler is, the improbabilities in the betting industry are unimaginable. There are over 1500 cryptocurrencies and this number is rapidly increasing on a daily basis. After calculating the possibility of growth and profit, an investor can easily purchase the digital coin he desires to own right from the comfort of his home with no intermediaries or involvement of any governmental or financial institutions.

Cryptocurrency investments provide ample unprecedented opportunities for investors. Storing cryptos in vaults or online wallets, waiting for its value to multiply may sound like a child’s play to many financial experts but it‘s better than the lottery, as it gives individuals a total control over their assets.

Furthermore, no matter how little your investment or how risky a cryptocurrency investment is, a skilled and hardworking person can make substantial returns in no time. New investment opportunities continue to evolve in the cryptocurrency space. This even gets better as digital coins are now easily procured with the development and installation of cryptocurrency automated teller machines (ATM).

bitcoin atm

In March, reports states that two cryptocurrency ATMs where installed in Georgia in order to make the exchange of bitcoins and Litecoins hassle-free with support for Ethereum and Dashcoin expected in the near future. Many online stores now allow customers to pay for goods with digital coins with lower fees compared to the traditional currencies.

In addition, a new concept known as Bitcoin IRA provides investment opportunities for retirees. It helps to create a cryptocurrency IRA investment account that can be benefited from retirement. Retirees will only have to pay fewer fees compared to that of the traditional currency plus, they just have to sit and watch their investment grow in the cryptocurrency space.

Cryptocoins are rapidly growing in terms of awareness, acceptability, and investments. It can now be used to make payments for products from local and international stores ranging from the purchase of groceries to the management of online contents as well as the procurement of digital assets.

Even with the risks, high volatility, scams and hacking activities in the cryptocurrency space, it still provides innumerable investment opportunities for its users and it’s believed by many cryptocurrency enthusiasts that this is just the beginning. The industries are projected to grow like wildfire over the next decade, providing new investment opportunities and revolutionizing financial institutions in ways that were practically impossible with the traditional currencies. Digital coins provide everybody with equal opportunity to own it and take part in the growth of the industry over a period of time.

The post Cryptocurrency Investing — Why Some Get Scammed While Others Get Rich appeared first on Crypto Investing Insider.

]]>
https://cryptoinvestinginsider.com/blog/cryptocurrency-investing-why-some-get-scammed-while-others-get-rich/feed/ 0