50行C#代碼構建小型區塊鏈

注:原文爲《50行Python代碼構建小型區塊鏈》,本文僅將Python實現改成C#。html

 

本文介紹瞭如何使用C#構建一個小型的區塊鏈技術,使用控制檯實現。git

Although some think blockchain is a solution waiting for problems, there’s no doubt that this novel technology is a marvel of computing. But, what exactly is a blockchain?
雖然有人認爲區塊鏈自己仍有不少問題須要解決,但毫無疑問,這種新穎的技術是計算機界的奇蹟。 可是,究竟什麼是一個區塊鏈?

Blockchain
a digital ledger in which transactions made in bitcoin or another cryptocurrency are recorded chronologically and publicly. >
區塊鏈一種數字記帳本,其中以比特幣或其餘加密方式按時間順序並公開記錄地進行交易。

In more general terms, it’s a public database where new data are stored in a container called a block and are added to an immutable chain (hence blockchain) with data added in the past. In the case of Bitcoin and other cryptocurrencies, these data are groups of transactions. But, the data can be of any type, of course.
通俗的講,區塊鏈是一個公共數據庫,其中新產生的數據存儲在稱爲塊的容器中,並被添加到具備已經存在數據的區塊構成的鏈中。在比特幣和其餘加密貨幣的狀況下,這些數據是一組交易。數據也能夠是任何類型的。算法


Blockchain technology has given rise to new, fully digital currencies like Bitcoin and Litecoin that aren’t issued or managed by a central authority. This brings new freedom to individuals who believe that today’s banking systems are a scam or subject to failure. Blockchain has also revolutionized distributed computing in the form of technologies like Ethereum, which has introduced interesting concepts like smart contracts.
區塊鏈技術已經帶來了全新的,徹底數字化的貨幣,如比特幣和萊特幣,它們不禁中央機構發行或管理的,這給相信今天的銀行體系是騙局或失敗的我的帶來了新的自由。區塊鏈也以像以太坊這樣的技術形式革新了分佈式計算,它引入了有趣的概念,如智能合約。數據庫


In this article, I’ll make a simple blockchain in less than 50 lines of Python 2 code. It’ll be called SnakeCoin.
在本文中,我將在不到50行的Python 2代碼(本文已用C#實現)中製做一個簡單的區塊鏈。這將被稱爲SnakeCoin。服務器


We’ll start by first defining what our blocks will look like. In blockchain, each block is stored with a timestamp and, optionally, an index. In SnakeCoin, we’re going to store both. And to help ensure integrity throughout the blockchain, each block will have a self-identifying hash. Like Bitcoin, each block’s hash will be a cryptographic hash of the block’s index, timestamp, data, and the hash of the previous block’s hash. Oh, and the data can be anything you want.
咱們首先定義咱們的區塊將是什麼樣子。在區塊鏈中,每一個塊都存儲有時間戳和可選的索引。在SnakeCoin中,咱們將同時存儲二者。而且爲了幫助確保整個塊鏈的完整性,每一個塊將具備自識別哈希值的功能。像比特幣同樣,每一個區塊將包括做爲區塊的索引的哈希值,時間戳,數據以及前一個塊的哈希值。哦,數據能夠是任何你想要的。app

 public class Block
    {
        public int index { get; set; }
        public string hash { get; set; }
        public long timestamp { get; set; }
        public string data { get; set; }
        public string previous_hash { get; set; }
        public Block(int index,long timestamp, string data, string previous_hash)
        {
            this.index = index;
            this.timestamp = timestamp;
            this.data = data;
            this.previous_hash = previous_hash;
            this.hash = HashBlock();
        }

        private string HashBlock()
        {
            return Sha256(index+timestamp+data+previous_hash);
        }
        public static string Sha256(string strData)
        {
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(strData);
            try
            {
                SHA256 sha256 = new SHA256CryptoServiceProvider();
                byte[] retVal = sha256.ComputeHash(bytValue);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetSHA256HashFromString() fail,error:" + ex.Message);
            }
        }
    }

Awesome! We have our block structure, but we’re creating a block chain. We need to start adding blocks to the actual chain. As I mentioned earlier, each block requires information from the previous block. But with that being said, a question arises: how does the first block in the blockchain get there? Well, the first block, or genesis block, is a special block. In many cases, it’s added manually or has unique logic allowing it to be added.
真棒!咱們已經有了塊結構了,可是咱們正在建立一個區塊鏈。咱們須要開始向實際的鏈條添加區塊。如前所述,每一個塊都須要上一個塊的信息。可是這就出現了一個問題:塊區中的第一個區塊怎麼來的?那麼,第一個區塊,或起創世區塊,是一個特殊的塊。在許多狀況下,它是手動添加的或具備容許添加的惟一邏輯。less


We’ll create a function that simply returns a genesis block to make things easy. This block is of index 0, and it has an arbitrary data value and an arbitrary value in the 「previous hash」 parameter.
爲了簡化,咱們將建立一個函數,只需返回一個創世區塊,該區塊的索引爲0,它在「previous hash」參數中具備任意數據值和任意值。dom

static Block CreateGenesisBlock() {
            return new Block(0, GetTimeStamp(), "GenesisBlock", "0");
        }

Now that we’re able to create a genesis block, we need a function that will generate succeeding blocks in the blockchain. This function will take the previous block in the chain as a parameter, create the data for the block to be generated, and return the new block with its appropriate data. When new blocks hash information from previous blocks, the integrity of the blockchain increases with each new block. If we didn’t do this, it would be easier for an outside party to 「change the past」 and replace our chain with an entirely new one of their own. This chain of hashes acts as cryptographic proof and helps ensure that once a block is added to the blockchain it cannot be replaced or removed.
如今咱們建立了一個創世區塊,咱們須要一個函數來生成區塊鏈中的後續區塊。該函數將將鏈中的前一個區塊做爲參數,建立要生成的區塊的數據,並返回具備其相應數據的新塊。新產生的區塊會存儲先前區塊中的哈希值,區塊鏈的完整性隨着每一個新的區塊而增長。若是咱們沒有這樣作,其餘人會很容易篡改歷史記錄,並用本身的全新數據替代咱們的鏈條。這個哈希鏈做爲加密證實,有助於確保一旦新區塊被添加到區塊鏈中,它不能被替換或刪除。分佈式

  static Block NextBlock(Block last_block)
        {
         return new Block(last_block.index + 1, GetTimeStamp(), "Hey! I'm block " + ++last_block.index, last_block.hash);
        }

That’s the majority of the hard work. Now, we can create our blockchain! In our case, the blockchain itself is a simple Python list. The first element of the list is the genesis block. And of course, we need to add the succeeding blocks. Because SnakeCoin is the tiniest blockchain, we’ll only add 20 new blocks. We can do this with a for loop.
這是本次任務的重心。如今咱們能夠建立咱們的區塊鏈!在咱們的例子中,區塊鏈自己就是一個簡單的Python列表。列表的第一個元素是創世區塊。固然,咱們須要添加後續的區塊。由於SnakeCoin是最小的區塊鏈,因此咱們只添加了20個新的塊。咱們能夠用for循環來作到這一點ide

 static void Main(string[] args)
        {
            List<Block> blockchain = new List<Block>();
            var genesisBlock = CreateGenesisBlock();
            blockchain.Add(genesisBlock);
            for (int i = 0; i < 20; i++)
            {
                Block block_to_add = NextBlock(blockchain[i]);
                blockchain.Add(block_to_add);
                Console.WriteLine(string.Format("Block #{0} has been added to the blockchain!",blockchain[i].index));
                Console.WriteLine(string.Format("Hash: {0}\n",block_to_add.hash));
            }
            Console.ReadKey();
        }

Let’s test what we’ve made so far.
咱們來測試一下已有成果。

There we go! Our blockchain works. If you want to see more information in the console, you could edit the complete source file and print each block’s timestamp or data.我去!咱們的區塊鏈生效了!若是要在控制檯中查看更多信息,能夠編輯完整的源文件並打印每一個塊的時間戳或數據。That’s about all that SnakeCoin has to offer. To make SnakeCoin scale to the size of today’s production blockchains, we’d have to add more features like a server layer to track changes to the chain on multiple machines and a proof-of-work algorithm to limit the amount of blocks added in a given time period.那就是SnakeCoin所提供的一切。爲了使SnakeCoin縮小到當此生產塊鏈的大小,咱們必須添加更多的功能,如服務器層,以跟蹤多臺機器上鍊的變化,並提供工做證實算法,以在給定時間段限制塊鏈數量。If you’d like to get more technical, you can view the original Bitcoin whitepaper here. Best of luck and happy hacking!若是您想得到更多技術細節,您能夠查看原始的比特幣白皮書。 祝好運!Thank you very much for reading!感謝閱讀!

相關文章
相關標籤/搜索