[
  {
    "path": ".gitattributes",
    "content": "###############################################################################\n# Set default behavior to automatically normalize line endings.\n###############################################################################\n* text=auto\n\n###############################################################################\n# Set default behavior for command prompt diff.\n#\n# This is need for earlier builds of msysgit that does not have it on by\n# default for csharp files.\n# Note: This is only used by command line\n###############################################################################\n#*.cs     diff=csharp\n\n###############################################################################\n# Set the merge driver for project and solution files\n#\n# Merging from the command prompt will add diff markers to the files if there\n# are conflicts (Merging from VS is not affected by the settings below, in VS\n# the diff markers are never inserted). Diff markers may cause the following \n# file extensions to fail to load in VS. An alternative would be to treat\n# these files as binary and thus will always conflict and require user\n# intervention with every merge. To do so, just uncomment the entries below\n###############################################################################\n#*.sln       merge=binary\n#*.csproj    merge=binary\n#*.vbproj    merge=binary\n#*.vcxproj   merge=binary\n#*.vcproj    merge=binary\n#*.dbproj    merge=binary\n#*.fsproj    merge=binary\n#*.lsproj    merge=binary\n#*.wixproj   merge=binary\n#*.modelproj merge=binary\n#*.sqlproj   merge=binary\n#*.wwaproj   merge=binary\n\n###############################################################################\n# behavior for image files\n#\n# image files are treated as binary by default.\n###############################################################################\n#*.jpg   binary\n#*.png   binary\n#*.gif   binary\n\n###############################################################################\n# diff behavior for common document formats\n# \n# Convert binary document formats to text before diffing them. This feature\n# is only available from the command line. Turn it on by uncommenting the \n# entries below.\n###############################################################################\n#*.doc   diff=astextplain\n#*.DOC   diff=astextplain\n#*.docx  diff=astextplain\n#*.DOCX  diff=astextplain\n#*.dot   diff=astextplain\n#*.DOT   diff=astextplain\n#*.pdf   diff=astextplain\n#*.PDF   diff=astextplain\n#*.rtf   diff=astextplain\n#*.RTF   diff=astextplain\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# dotenv\n.env\n\n# virtualenv\n.venv\nvenv/\nENV/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n\n# PyCharm\n.idea/\n\nnode_modules/\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: python\n\npython:\n  - 3.6\n  - nightly\n\ninstall:\n  - pip install pipenv\n  - pipenv install --dev\n\nscript:\n  - pipenv run python -m unittest\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM python:3.6-alpine\n\nWORKDIR /app\n\n# Install dependencies.\nADD requirements.txt /app\nRUN cd /app && \\\n    pip install -r requirements.txt\n\n# Add actual source code.\nADD blockchain.py /app\n\nEXPOSE 5000\n\nCMD [\"python\", \"blockchain.py\", \"--port\", \"5000\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 Daniel van Flymen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Pipfile",
    "content": "[[source]]\nurl = \"https://pypi.python.org/simple\"\nverify_ssl = true\nname = \"pypi\"\n\n[dev-packages]\n\n[requires]\npython_version = \"3.6\"\n\n[packages]\n\nflask = \"==0.12.2\"\nrequests = \"==2.18.4\"\n\n"
  },
  {
    "path": "README.md",
    "content": "# Are you looking for the source code for my book?\n\nPlease find it here: https://github.com/dvf/blockchain-book\n\nThe book is available on Amazon: https://www.amazon.com/Learn-Blockchain-Building-Understanding-Cryptocurrencies/dp/1484251709\n\n# Learn Blockchains by Building One\n\n[![Build Status](https://travis-ci.org/dvf/blockchain.svg?branch=master)](https://travis-ci.org/dvf/blockchain)\n\nThis is the source code for my post on [Building a Blockchain](https://medium.com/p/117428612f46). \n\n## Installation\n\n1. Make sure [Python 3.6+](https://www.python.org/downloads/) is installed. \n2. Install [pipenv](https://github.com/kennethreitz/pipenv). \n\n```\n$ pip install pipenv \n```\n3. Install requirements  \n```\n$ pipenv install \n``` \n\n4. Run the server:\n    * `$ pipenv run python blockchain.py` \n    * `$ pipenv run python blockchain.py -p 5001`\n    * `$ pipenv run python blockchain.py --port 5002`\n    \n## Docker\n\nAnother option for running this blockchain program is to use Docker.  Follow the instructions below to create a local Docker container:\n\n1. Clone this repository\n2. Build the docker container\n\n```\n$ docker build -t blockchain .\n```\n\n3. Run the container\n\n```\n$ docker run --rm -p 80:5000 blockchain\n```\n\n4. To add more instances, vary the public port number before the colon:\n\n```\n$ docker run --rm -p 81:5000 blockchain\n$ docker run --rm -p 82:5000 blockchain\n$ docker run --rm -p 83:5000 blockchain\n```\n\n## Installation (C# Implementation)\n\n1. Install a free copy of Visual Studio IDE (Community Edition):\nhttps://www.visualstudio.com/vs/\n\n2. Once installed, open the solution file (BlockChain.sln) using the File > Open > Project/Solution menu options within Visual Studio.\n\n3. From within the \"Solution Explorer\", right click the BlockChain.Console project and select the \"Set As Startup Project\" option.\n\n4. Click the \"Start\" button, or hit F5 to run. The program executes in a console window, and is controlled via HTTP with the same commands as the Python version.\n\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n"
  },
  {
    "path": "blockchain.py",
    "content": "import hashlib\nimport json\nfrom time import time\nfrom urllib.parse import urlparse\nfrom uuid import uuid4\n\nimport requests\nfrom flask import Flask, jsonify, request\n\n\nclass Blockchain:\n    def __init__(self):\n        self.current_transactions = []\n        self.chain = []\n        self.nodes = set()\n\n        # Create the genesis block\n        self.new_block(previous_hash='1', proof=100)\n\n    def register_node(self, address):\n        \"\"\"\n        Add a new node to the list of nodes\n\n        :param address: Address of node. Eg. 'http://192.168.0.5:5000'\n        \"\"\"\n\n        parsed_url = urlparse(address)\n        if parsed_url.netloc:\n            self.nodes.add(parsed_url.netloc)\n        elif parsed_url.path:\n            # Accepts an URL without scheme like '192.168.0.5:5000'.\n            self.nodes.add(parsed_url.path)\n        else:\n            raise ValueError('Invalid URL')\n\n\n    def valid_chain(self, chain):\n        \"\"\"\n        Determine if a given blockchain is valid\n\n        :param chain: A blockchain\n        :return: True if valid, False if not\n        \"\"\"\n\n        last_block = chain[0]\n        current_index = 1\n\n        while current_index < len(chain):\n            block = chain[current_index]\n            print(f'{last_block}')\n            print(f'{block}')\n            print(\"\\n-----------\\n\")\n            # Check that the hash of the block is correct\n            last_block_hash = self.hash(last_block)\n            if block['previous_hash'] != last_block_hash:\n                return False\n\n            # Check that the Proof of Work is correct\n            if not self.valid_proof(last_block['proof'], block['proof'], last_block_hash):\n                return False\n\n            last_block = block\n            current_index += 1\n\n        return True\n\n    def resolve_conflicts(self):\n        \"\"\"\n        This is our consensus algorithm, it resolves conflicts\n        by replacing our chain with the longest one in the network.\n\n        :return: True if our chain was replaced, False if not\n        \"\"\"\n\n        neighbours = self.nodes\n        new_chain = None\n\n        # We're only looking for chains longer than ours\n        max_length = len(self.chain)\n\n        # Grab and verify the chains from all the nodes in our network\n        for node in neighbours:\n            response = requests.get(f'http://{node}/chain')\n\n            if response.status_code == 200:\n                length = response.json()['length']\n                chain = response.json()['chain']\n\n                # Check if the length is longer and the chain is valid\n                if length > max_length and self.valid_chain(chain):\n                    max_length = length\n                    new_chain = chain\n\n        # Replace our chain if we discovered a new, valid chain longer than ours\n        if new_chain:\n            self.chain = new_chain\n            return True\n\n        return False\n\n    def new_block(self, proof, previous_hash):\n        \"\"\"\n        Create a new Block in the Blockchain\n\n        :param proof: The proof given by the Proof of Work algorithm\n        :param previous_hash: Hash of previous Block\n        :return: New Block\n        \"\"\"\n\n        block = {\n            'index': len(self.chain) + 1,\n            'timestamp': time(),\n            'transactions': self.current_transactions,\n            'proof': proof,\n            'previous_hash': previous_hash or self.hash(self.chain[-1]),\n        }\n\n        # Reset the current list of transactions\n        self.current_transactions = []\n\n        self.chain.append(block)\n        return block\n\n    def new_transaction(self, sender, recipient, amount):\n        \"\"\"\n        Creates a new transaction to go into the next mined Block\n\n        :param sender: Address of the Sender\n        :param recipient: Address of the Recipient\n        :param amount: Amount\n        :return: The index of the Block that will hold this transaction\n        \"\"\"\n        self.current_transactions.append({\n            'sender': sender,\n            'recipient': recipient,\n            'amount': amount,\n        })\n\n        return self.last_block['index'] + 1\n\n    @property\n    def last_block(self):\n        return self.chain[-1]\n\n    @staticmethod\n    def hash(block):\n        \"\"\"\n        Creates a SHA-256 hash of a Block\n\n        :param block: Block\n        \"\"\"\n\n        # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes\n        block_string = json.dumps(block, sort_keys=True).encode()\n        return hashlib.sha256(block_string).hexdigest()\n\n    def proof_of_work(self, last_block):\n        \"\"\"\n        Simple Proof of Work Algorithm:\n\n         - Find a number p' such that hash(pp') contains leading 4 zeroes\n         - Where p is the previous proof, and p' is the new proof\n         \n        :param last_block: <dict> last Block\n        :return: <int>\n        \"\"\"\n\n        last_proof = last_block['proof']\n        last_hash = self.hash(last_block)\n\n        proof = 0\n        while self.valid_proof(last_proof, proof, last_hash) is False:\n            proof += 1\n\n        return proof\n\n    @staticmethod\n    def valid_proof(last_proof, proof, last_hash):\n        \"\"\"\n        Validates the Proof\n\n        :param last_proof: <int> Previous Proof\n        :param proof: <int> Current Proof\n        :param last_hash: <str> The hash of the Previous Block\n        :return: <bool> True if correct, False if not.\n\n        \"\"\"\n\n        guess = f'{last_proof}{proof}{last_hash}'.encode()\n        guess_hash = hashlib.sha256(guess).hexdigest()\n        return guess_hash[:4] == \"0000\"\n\n\n# Instantiate the Node\napp = Flask(__name__)\n\n# Generate a globally unique address for this node\nnode_identifier = str(uuid4()).replace('-', '')\n\n# Instantiate the Blockchain\nblockchain = Blockchain()\n\n\n@app.route('/mine', methods=['GET'])\ndef mine():\n    # We run the proof of work algorithm to get the next proof...\n    last_block = blockchain.last_block\n    proof = blockchain.proof_of_work(last_block)\n\n    # We must receive a reward for finding the proof.\n    # The sender is \"0\" to signify that this node has mined a new coin.\n    blockchain.new_transaction(\n        sender=\"0\",\n        recipient=node_identifier,\n        amount=1,\n    )\n\n    # Forge the new Block by adding it to the chain\n    previous_hash = blockchain.hash(last_block)\n    block = blockchain.new_block(proof, previous_hash)\n\n    response = {\n        'message': \"New Block Forged\",\n        'index': block['index'],\n        'transactions': block['transactions'],\n        'proof': block['proof'],\n        'previous_hash': block['previous_hash'],\n    }\n    return jsonify(response), 200\n\n\n@app.route('/transactions/new', methods=['POST'])\ndef new_transaction():\n    values = request.get_json()\n\n    # Check that the required fields are in the POST'ed data\n    required = ['sender', 'recipient', 'amount']\n    if not all(k in values for k in required):\n        return 'Missing values', 400\n\n    # Create a new Transaction\n    index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])\n\n    response = {'message': f'Transaction will be added to Block {index}'}\n    return jsonify(response), 201\n\n\n@app.route('/chain', methods=['GET'])\ndef full_chain():\n    response = {\n        'chain': blockchain.chain,\n        'length': len(blockchain.chain),\n    }\n    return jsonify(response), 200\n\n\n@app.route('/nodes/register', methods=['POST'])\ndef register_nodes():\n    values = request.get_json()\n\n    nodes = values.get('nodes')\n    if nodes is None:\n        return \"Error: Please supply a valid list of nodes\", 400\n\n    for node in nodes:\n        blockchain.register_node(node)\n\n    response = {\n        'message': 'New nodes have been added',\n        'total_nodes': list(blockchain.nodes),\n    }\n    return jsonify(response), 201\n\n\n@app.route('/nodes/resolve', methods=['GET'])\ndef consensus():\n    replaced = blockchain.resolve_conflicts()\n\n    if replaced:\n        response = {\n            'message': 'Our chain was replaced',\n            'new_chain': blockchain.chain\n        }\n    else:\n        response = {\n            'message': 'Our chain is authoritative',\n            'chain': blockchain.chain\n        }\n\n    return jsonify(response), 200\n\n\nif __name__ == '__main__':\n    from argparse import ArgumentParser\n\n    parser = ArgumentParser()\n    parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on')\n    args = parser.parse_args()\n    port = args.port\n\n    app.run(host='0.0.0.0', port=port)\n"
  },
  {
    "path": "csharp/BlockChain/Block.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\n\nnamespace BlockChainDemo\n{\n    public class Block\n    {\n        public int Index { get; set; }\n        public DateTime Timestamp { get; set; }\n        public List<Transaction> Transactions { get; set; }\n        public int Proof { get; set; }\n        public string PreviousHash { get; set; }\n\n        public override string ToString()\n        {\n            return $\"{Index} [{Timestamp.ToString(\"yyyy-MM-dd HH:mm:ss\")}] Proof: {Proof} | PrevHash: {PreviousHash} | Trx: {Transactions.Count}\";\n        }\n    }\n}"
  },
  {
    "path": "csharp/BlockChain/BlockChain.cs",
    "content": "﻿using Newtonsoft.Json;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace BlockChainDemo\n{\n    public class BlockChain\n    {\n        private List<Transaction> _currentTransactions = new List<Transaction>();\n        private List<Block> _chain = new List<Block>();\n        private List<Node> _nodes = new List<Node>();\n        private Block _lastBlock => _chain.Last();\n\n        public string NodeId { get; private set; }\n\n        //ctor\n        public BlockChain()\n        {\n            NodeId = Guid.NewGuid().ToString().Replace(\"-\", \"\");\n            CreateNewBlock(proof: 100, previousHash: \"1\"); //genesis block\n        }\n\n        //private functionality\n        private void RegisterNode(string address)\n        {\n            _nodes.Add(new Node { Address = new Uri(address) });\n        }\n\n        private bool IsValidChain(List<Block> chain)\n        {\n            Block block = null;\n            Block lastBlock = chain.First();\n            int currentIndex = 1;\n            while (currentIndex < chain.Count)\n            {\n                block = chain.ElementAt(currentIndex);\n                Debug.WriteLine($\"{lastBlock}\");\n                Debug.WriteLine($\"{block}\");\n                Debug.WriteLine(\"----------------------------\");\n\n                //Check that the hash of the block is correct\n                if (block.PreviousHash != GetHash(lastBlock))\n                    return false;\n\n                //Check that the Proof of Work is correct\n                if (!IsValidProof(lastBlock.Proof, block.Proof, lastBlock.PreviousHash))\n                    return false;\n\n                lastBlock = block;\n                currentIndex++;\n            }\n\n            return true;\n        }\n\n        private bool ResolveConflicts()\n        {\n            List<Block> newChain = null;\n            int maxLength = _chain.Count;\n\n            foreach (Node node in _nodes)\n            {\n                var url = new Uri(node.Address, \"/chain\");\n                var request = (HttpWebRequest)WebRequest.Create(url);\n                var response = (HttpWebResponse)request.GetResponse();\n\n                if (response.StatusCode == HttpStatusCode.OK)\n                {\n                    var model = new\n                    {\n                        chain = new List<Block>(),\n                        length = 0\n                    };\n                    string json = new StreamReader(response.GetResponseStream()).ReadToEnd();\n                    var data = JsonConvert.DeserializeAnonymousType(json, model);\n\n                    if (data.chain.Count > _chain.Count && IsValidChain(data.chain))\n                    {\n                        maxLength = data.chain.Count;\n                        newChain = data.chain;\n                    }\n                }\n            }\n\n            if (newChain != null)\n            {\n                _chain = newChain;\n                return true;\n            }\n\n            return false;\n        }\n\n        private Block CreateNewBlock(int proof, string previousHash = null)\n        {\n            var block = new Block\n            {\n                Index = _chain.Count,\n                Timestamp = DateTime.UtcNow,\n                Transactions = _currentTransactions.ToList(),\n                Proof = proof,\n                PreviousHash = previousHash ?? GetHash(_chain.Last())\n            };\n\n            _currentTransactions.Clear();\n            _chain.Add(block);\n            return block;\n        }\n\n        private int CreateProofOfWork(int lastProof, string previousHash)\n        {\n            int proof = 0;\n            while (!IsValidProof(lastProof, proof, previousHash))\n                proof++;\n\n            return proof;\n        }\n\n        private bool IsValidProof(int lastProof, int proof, string previousHash)\n        {\n            string guess = $\"{lastProof}{proof}{previousHash}\";\n            string result = GetSha256(guess);\n            return result.StartsWith(\"0000\");\n        }\n\n        private string GetHash(Block block)\n        {\n            string blockText = JsonConvert.SerializeObject(block);\n            return GetSha256(blockText);\n        }\n\n        private string GetSha256(string data)\n        {\n            var sha256 = new SHA256Managed();\n            var hashBuilder = new StringBuilder();\n\n            byte[] bytes = Encoding.Unicode.GetBytes(data);\n            byte[] hash = sha256.ComputeHash(bytes);\n\n            foreach (byte x in hash)\n                hashBuilder.Append($\"{x:x2}\");\n\n            return hashBuilder.ToString();\n        }\n\n        //web server calls\n        internal string Mine()\n        {\n            int proof = CreateProofOfWork(_lastBlock.Proof, _lastBlock.PreviousHash);\n\n            CreateTransaction(sender: \"0\", recipient: NodeId, amount: 1);\n            Block block = CreateNewBlock(proof /*, _lastBlock.PreviousHash*/);\n\n            var response = new\n            {\n                Message = \"New Block Forged\",\n                Index = block.Index,\n                Transactions = block.Transactions.ToArray(),\n                Proof = block.Proof,\n                PreviousHash = block.PreviousHash\n            };\n\n            return JsonConvert.SerializeObject(response);\n        }\n\n        internal string GetFullChain()\n        {\n            var response = new\n            {\n                chain = _chain.ToArray(),\n                length = _chain.Count\n            };\n\n            return JsonConvert.SerializeObject(response);\n        }\n\n        internal string RegisterNodes(string[] nodes)\n        {\n            var builder = new StringBuilder();\n            foreach (string node in nodes)\n            {\n                string url = $\"http://{node}\";\n                RegisterNode(url);\n                builder.Append($\"{url}, \");\n            }\n\n            builder.Insert(0, $\"{nodes.Count()} new nodes have been added: \");\n            string result = builder.ToString();\n            return result.Substring(0, result.Length - 2);\n        }\n\n        internal string Consensus()\n        {\n            bool replaced = ResolveConflicts();\n            string message = replaced ? \"was replaced\" : \"is authoritive\";\n            \n            var response = new\n            {\n                Message = $\"Our chain {message}\",\n                Chain = _chain\n            };\n\n            return JsonConvert.SerializeObject(response);\n        }\n\n        internal int CreateTransaction(string sender, string recipient, int amount)\n        {\n            var transaction = new Transaction\n            {\n                Sender = sender,\n                Recipient = recipient,\n                Amount = amount\n            };\n\n            _currentTransactions.Add(transaction);\n\n            return _lastBlock != null ? _lastBlock.Index + 1 : 0;\n        }\n    }\n}\n"
  },
  {
    "path": "csharp/BlockChain/BlockChain.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{E06FC4CE-77D0-4A64-94A6-32A08920E481}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>BlockChainDemo</RootNamespace>\n    <AssemblyName>BlockChainDemo</AssemblyName>\n    <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <SccProjectName>SAK</SccProjectName>\n    <SccLocalPath>SAK</SccLocalPath>\n    <SccAuxPath>SAK</SccAuxPath>\n    <SccProvider>SAK</SccProvider>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>bin\\Debug\\</OutputPath>\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>bin\\Release\\</OutputPath>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\packages\\Newtonsoft.Json.10.0.3\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"TinyWebServer, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <HintPath>..\\packages\\TinyWebServer.dll.1.0.1\\lib\\net40\\TinyWebServer.dll</HintPath>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Block.cs\" />\n    <Compile Include=\"BlockChain.cs\" />\n    <Compile Include=\"Node.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Transaction.cs\" />\n    <Compile Include=\"WebServer.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "csharp/BlockChain/Node.cs",
    "content": "﻿using System;\n\nnamespace BlockChainDemo\n{\n    public class Node\n    {\n        public Uri Address { get; set; }\n    }\n}"
  },
  {
    "path": "csharp/BlockChain/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle(\"BlockChain\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"\")]\n[assembly: AssemblyProduct(\"BlockChain\")]\n[assembly: AssemblyCopyright(\"Copyright ©  2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// Setting ComVisible to false makes the types in this assembly not visible \n// to COM components.  If you need to access a type in this assembly from \n// COM, set the ComVisible attribute to true on that type.\n[assembly: ComVisible(false)]\n\n// The following GUID is for the ID of the typelib if this project is exposed to COM\n[assembly: Guid(\"e06fc4ce-77d0-4a64-94a6-32a08920e481\")]\n\n// Version information for an assembly consists of the following four values:\n//\n//      Major Version\n//      Minor Version \n//      Build Number\n//      Revision\n//\n// You can specify all the values or you can default the Build and Revision Numbers \n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "csharp/BlockChain/Transaction.cs",
    "content": "﻿namespace BlockChainDemo\n{\n    public class Transaction\n    {\n        public int Amount { get; set; }\n        public string Recipient { get; set; }\n        public string Sender { get; set; }\n    }\n}"
  },
  {
    "path": "csharp/BlockChain/WebServer.cs",
    "content": "﻿using Newtonsoft.Json;\nusing System.Configuration;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\n\nnamespace BlockChainDemo\n{\n    public class WebServer\n    {\n        public WebServer(BlockChain chain)\n        {\n            var settings = ConfigurationManager.AppSettings;\n            string host = settings[\"host\"]?.Length > 1 ? settings[\"host\"] : \"localhost\";\n            string port = settings[\"port\"]?.Length > 1 ? settings[\"port\"] : \"12345\";\n\n            var server = new TinyWebServer.WebServer(request =>\n                {\n                    string path = request.Url.PathAndQuery.ToLower();\n                    string query = \"\";\n                    string json = \"\";\n                    if (path.Contains(\"?\"))\n                    {\n                        string[] parts = path.Split('?');\n                        path = parts[0];\n                        query = parts[1];\n                    }\n\n                    switch (path)\n                    {\n                        //GET: http://localhost:12345/mine\n                        case \"/mine\":\n                            return chain.Mine();\n\n                        //POST: http://localhost:12345/transactions/new\n                        //{ \"Amount\":123, \"Recipient\":\"ebeabf5cc1d54abdbca5a8fe9493b479\", \"Sender\":\"31de2e0ef1cb4937830fcfd5d2b3b24f\" }\n                        case \"/transactions/new\":\n                            if (request.HttpMethod != HttpMethod.Post.Method)\n                                return $\"{new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)}\";\n\n                            json = new StreamReader(request.InputStream).ReadToEnd();\n                            Transaction trx = JsonConvert.DeserializeObject<Transaction>(json);\n                            int blockId = chain.CreateTransaction(trx.Sender, trx.Recipient, trx.Amount);\n                            return $\"Your transaction will be included in block {blockId}\";\n\n                        //GET: http://localhost:12345/chain\n                        case \"/chain\":\n                            return chain.GetFullChain();\n\n                        //POST: http://localhost:12345/nodes/register\n                        //{ \"Urls\": [\"localhost:54321\", \"localhost:54345\", \"localhost:12321\"] }\n                        case \"/nodes/register\":\n                            if (request.HttpMethod != HttpMethod.Post.Method)\n                                return $\"{new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)}\";\n\n                            json = new StreamReader(request.InputStream).ReadToEnd();\n                            var urlList = new { Urls = new string[0] };\n                            var obj = JsonConvert.DeserializeAnonymousType(json, urlList);\n                            return chain.RegisterNodes(obj.Urls);\n\n                        //GET: http://localhost:12345/nodes/resolve\n                        case \"/nodes/resolve\":\n                            return chain.Consensus();\n                    }\n\n                    return \"\";\n                },\n                $\"http://{host}:{port}/mine/\",\n                $\"http://{host}:{port}/transactions/new/\",\n                $\"http://{host}:{port}/chain/\",\n                $\"http://{host}:{port}/nodes/register/\",\n                $\"http://{host}:{port}/nodes/resolve/\"\n            );\n\n            server.Run();\n        }\n    }\n}\n"
  },
  {
    "path": "csharp/BlockChain/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Newtonsoft.Json\" version=\"10.0.3\" targetFramework=\"net451\" />\n  <package id=\"TinyWebServer.dll\" version=\"1.0.1\" targetFramework=\"net451\" />\n</packages>"
  },
  {
    "path": "csharp/BlockChain.Console/App.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5.1\"/>\n    </startup>\n  <appSettings>\n    <add key=\"host\" value=\"localhost\" />\n    <add key=\"port\" value=\"12345\" />\n  </appSettings>\n</configuration>\n"
  },
  {
    "path": "csharp/BlockChain.Console/BlockChain.Console.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{D0C795A0-6F20-4A8E-BE44-801678754DA4}</ProjectGuid>\n    <OutputType>Exe</OutputType>\n    <RootNamespace>BlockChainDemo.Console</RootNamespace>\n    <AssemblyName>BlockChainDemo.Console</AssemblyName>\n    <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\n    <SccProjectName>SAK</SccProjectName>\n    <SccLocalPath>SAK</SccLocalPath>\n    <SccAuxPath>SAK</SccAuxPath>\n    <SccProvider>SAK</SccProvider>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>bin\\Debug\\</OutputPath>\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>bin\\Release\\</OutputPath>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Program.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\BlockChain\\BlockChain.csproj\">\n      <Project>{e06fc4ce-77d0-4a64-94a6-32a08920e481}</Project>\n      <Name>BlockChain</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "csharp/BlockChain.Console/Program.cs",
    "content": "﻿namespace BlockChainDemo.Console\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var chain = new BlockChain();\n            var server = new WebServer(chain);\n            System.Console.Read();\n        }\n    }\n}\n"
  },
  {
    "path": "csharp/BlockChain.Console/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// General Information about an assembly is controlled through the following\n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle(\"BlockChain.Console\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"\")]\n[assembly: AssemblyProduct(\"BlockChain.Console\")]\n[assembly: AssemblyCopyright(\"Copyright ©  2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// Setting ComVisible to false makes the types in this assembly not visible\n// to COM components.  If you need to access a type in this assembly from\n// COM, set the ComVisible attribute to true on that type.\n[assembly: ComVisible(false)]\n\n// The following GUID is for the ID of the typelib if this project is exposed to COM\n[assembly: Guid(\"d0c795a0-6f20-4a8e-be44-801678754da4\")]\n\n// Version information for an assembly consists of the following four values:\n//\n//      Major Version\n//      Minor Version\n//      Build Number\n//      Revision\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "csharp/BlockChain.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 15\nVisualStudioVersion = 15.0.27004.2008\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"BlockChain\", \"BlockChain\\BlockChain.csproj\", \"{E06FC4CE-77D0-4A64-94A6-32A08920E481}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"BlockChain.Console\", \"BlockChain.Console\\BlockChain.Console.csproj\", \"{D0C795A0-6F20-4A8E-BE44-801678754DA4}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|Any CPU = Debug|Any CPU\n\t\tRelease|Any CPU = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{E06FC4CE-77D0-4A64-94A6-32A08920E481}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{E06FC4CE-77D0-4A64-94A6-32A08920E481}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{E06FC4CE-77D0-4A64-94A6-32A08920E481}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{E06FC4CE-77D0-4A64-94A6-32A08920E481}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{D0C795A0-6F20-4A8E-BE44-801678754DA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{D0C795A0-6F20-4A8E-BE44-801678754DA4}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{D0C795A0-6F20-4A8E-BE44-801678754DA4}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{D0C795A0-6F20-4A8E-BE44-801678754DA4}.Release|Any CPU.Build.0 = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {7FB3650B-CAFB-4A71-940B-0CA6F0377422}\n\tEndGlobalSection\n\tGlobalSection(TeamFoundationVersionControl) = preSolution\n\t\tSccNumberOfProjects = 3\n\t\tSccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}\n\t\tSccTeamFoundationServer = https://devfire.visualstudio.com/\n\t\tSccLocalPath0 = .\n\t\tSccProjectUniqueName1 = BlockChain\\\\BlockChain.csproj\n\t\tSccProjectName1 = BlockChain\n\t\tSccLocalPath1 = BlockChain\n\t\tSccProjectUniqueName2 = BlockChain.Console\\\\BlockChain.Console.csproj\n\t\tSccProjectName2 = BlockChain.Console\n\t\tSccLocalPath2 = BlockChain.Console\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "js/blockchain.js",
    "content": "const crypto = require(\"crypto\");\n\n\nclass Blockchain {\n    constructor() {\n        this.chain = [];\n        this.pendingTransactions = [];\n        this.newBlock();\n        this.peers = new Set();\n    }\n\n    /**\n     * Adds a node to our peer table\n     */\n    addPeer(host) {\n        this.peers.add(host);\n    }\n\n    /**\n     * Adds a node to our peer table\n     */\n    getPeers() {\n        return Array.from(this.peers);\n    }\n\n    /**\n     * Creates a new block containing any outstanding transactions\n     */\n    newBlock(previousHash, nonce = null) {\n        let block = {\n            index: this.chain.length,\n            timestamp: new Date().toISOString(),\n            transactions: this.pendingTransactions,\n            previousHash,\n            nonce\n        };\n\n        block.hash = Blockchain.hash(block);\n\n        console.log(`Created block ${block.index}`);\n\n        // Add the new block to the blockchain\n        this.chain.push(block);\n\n        // Reset pending transactions\n        this.pendingTransactions = [];\n    }\n\n    /**\n     * Generates a SHA-256 hash of the block\n     */\n    static hash(block) {\n        const blockString = JSON.stringify(block, Object.keys(block).sort());\n        return crypto.createHash(\"sha256\").update(blockString).digest(\"hex\");\n    }\n\n    /**\n     * Returns the last block in the chain\n     */\n    lastBlock() {\n        return this.chain.length && this.chain[this.chain.length - 1];\n    }\n\n    /**\n     * Determines if a hash begins with a \"difficulty\" number of 0s\n     *\n     * @param hashOfBlock: the hash of the block (hex string)\n     * @param difficulty: an integer defining the difficulty\n     */\n    static powIsAcceptable(hashOfBlock, difficulty) {\n        return hashOfBlock.slice(0, difficulty) === \"0\".repeat(difficulty);\n    }\n\n    /**\n     * Generates a random 32 byte string\n     */\n    static nonce() {\n        return crypto.createHash(\"sha256\").update(crypto.randomBytes(32)).digest(\"hex\");\n    }\n\n    /**\n     * Proof of Work mining algorithm\n     *\n     * We hash the block with random string until the hash begins with\n     * a \"difficulty\" number of 0s.\n     */\n    mine(blockToMine = null, difficulty = 4) {\n        const block = blockToMine || this.lastBlock();\n\n        while (true) {\n            block.nonce = Blockchain.nonce();\n            if (Blockchain.powIsAcceptable(Blockchain.hash(block), difficulty)) {\n                console.log(\"We mined a block!\")\n                console.log(` - Block hash: ${Blockchain.hash(block)}`);\n                console.log(` - nonce:      ${block.nonce}`);\n                return block;\n            }\n        }\n    }\n}\n\nmodule.exports = Blockchain;\n"
  },
  {
    "path": "js/index.js",
    "content": "const Blockchain = require(\"./blockchain\");\nconst {send} = require(\"micro\");\n\nconst blockchain = new Blockchain();\n\n\nmodule.exports = async (request, response) => {\n    const route = request.url;\n\n    // Keep track of the peers that have contacted us\n    blockchain.addPeer(request.headers.host);\n\n    let output;\n\n    switch (route) {\n        case \"/new_block\":\n            output = blockchain.newBlock();\n            break;\n\n        case \"/last_block\":\n            output = blockchain.lastBlock();\n            break;\n\n        case \"/get_peers\":\n            output = blockchain.getPeers();\n            break;\n\n        case \"/submit_transaction\":\n            output = blockchain.addTransaction(transaction);\n            break;\n\n        default:\n            output = blockchain.lastBlock();\n\n    }\n    send(response, 200, output);\n};\n"
  },
  {
    "path": "js/package.json",
    "content": "{\n  \"name\": \"blockchain\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"dev\": \"nodemon blockchain.js\",\n    \"server\": \"micro-dev\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"micro\": \"^9.3.4\",\n    \"micro-dev\": \"^3.0.0\",\n    \"nodemon\": \"^1.19.0\"\n  }\n}\n"
  },
  {
    "path": "requirements.txt",
    "content": "flask==0.12.2\nrequests==2.18.4\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/test_blockchain.py",
    "content": "import hashlib\nimport json\nfrom unittest import TestCase\n\nfrom blockchain import Blockchain\n\n\nclass BlockchainTestCase(TestCase):\n\n    def setUp(self):\n        self.blockchain = Blockchain()\n\n    def create_block(self, proof=123, previous_hash='abc'):\n        self.blockchain.new_block(proof, previous_hash)\n\n    def create_transaction(self, sender='a', recipient='b', amount=1):\n        self.blockchain.new_transaction(\n            sender=sender,\n            recipient=recipient,\n            amount=amount\n        )\n\n\nclass TestRegisterNodes(BlockchainTestCase):\n\n    def test_valid_nodes(self):\n        blockchain = Blockchain()\n\n        blockchain.register_node('http://192.168.0.1:5000')\n\n        self.assertIn('192.168.0.1:5000', blockchain.nodes)\n\n    def test_malformed_nodes(self):\n        blockchain = Blockchain()\n\n        blockchain.register_node('http//192.168.0.1:5000')\n\n        self.assertNotIn('192.168.0.1:5000', blockchain.nodes)\n\n    def test_idempotency(self):\n        blockchain = Blockchain()\n\n        blockchain.register_node('http://192.168.0.1:5000')\n        blockchain.register_node('http://192.168.0.1:5000')\n\n        assert len(blockchain.nodes) == 1\n\n\nclass TestBlocksAndTransactions(BlockchainTestCase):\n\n    def test_block_creation(self):\n        self.create_block()\n\n        latest_block = self.blockchain.last_block\n\n        # The genesis block is create at initialization, so the length should be 2\n        assert len(self.blockchain.chain) == 2\n        assert latest_block['index'] == 2\n        assert latest_block['timestamp'] is not None\n        assert latest_block['proof'] == 123\n        assert latest_block['previous_hash'] == 'abc'\n\n    def test_create_transaction(self):\n        self.create_transaction()\n\n        transaction = self.blockchain.current_transactions[-1]\n\n        assert transaction\n        assert transaction['sender'] == 'a'\n        assert transaction['recipient'] == 'b'\n        assert transaction['amount'] == 1\n\n    def test_block_resets_transactions(self):\n        self.create_transaction()\n\n        initial_length = len(self.blockchain.current_transactions)\n\n        self.create_block()\n\n        current_length = len(self.blockchain.current_transactions)\n\n        assert initial_length == 1\n        assert current_length == 0\n\n    def test_return_last_block(self):\n        self.create_block()\n\n        created_block = self.blockchain.last_block\n\n        assert len(self.blockchain.chain) == 2\n        assert created_block is self.blockchain.chain[-1]\n\n\nclass TestHashingAndProofs(BlockchainTestCase):\n\n    def test_hash_is_correct(self):\n        self.create_block()\n\n        new_block = self.blockchain.last_block\n        new_block_json = json.dumps(self.blockchain.last_block, sort_keys=True).encode()\n        new_hash = hashlib.sha256(new_block_json).hexdigest()\n\n        assert len(new_hash) == 64\n        assert new_hash == self.blockchain.hash(new_block)\n"
  }
]