ITPub博客

首页 > IT职业 > IT职场 > 50行ruby代码开发一个区块链

50行ruby代码开发一个区块链

IT职场 作者:longmanma 时间:2021-09-09 09:15:06 0 删除 编辑


区块链是什么?作为一个Ruby开发者,理解区块链的最好办法,就是亲自动手实现一个。只需要50行Ruby代码你就能彻底理解区块链的核心原理!

区块链 = 区块组成的链表?

blockchain.ruby:

class Block

  attr_reader :timestamp
  attr_reader :data
  attr_reader :previous_hash
  attr_reader :hash

  def initialize(data, previous_hash)
    @timestamp     = Time.now
    @data          = data
    @previous_hash = previous_hash
    @hash          = calc_hash  end

  def self.first( data="Genesis" )    # create genesis (big bang! first) block
    ## note: uses all zero for previous_hash ("0")
    Block.new( data, "0000000000000000000000000000000000000000000000000000000000000000" )  end

  def self.next( previous, data="Transaction Data..." )
    Block.new( data, previous.hash )  endprivate  def calc_hash
    sha = Digest::SHA256.new
    sha.update( @timestamp.to_s + @previous_hash + @data )
    sha.hexdigest  endend  # class Block####### let's get started##   build a blockchain a block at a timeb0 = Block.first( "Genesis" )
b1 = Block.next( b0, "Transaction Data..." )
b2 = Block.next( b1, "Transaction Data......" )
b3 = Block.next( b2, "More Transaction Data..." )

blockchain = [b0, b1, b2, b3]

pp blockchain

执行上面程序:

~$ ruby blockchain.rb

将会输出类似下面的结果:

[#<0x1eed2a0><0x1eec9a0><0x1eec838><0x1eec6d0>



<0x1e204f0><0x1e56e20><0x1e2bd58><0x1fa8338>



来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2730/viewspace-2801232/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: php常用小程序
请登录后发表评论 登录
全部评论

注册时间:2019-12-18

  • 博文量
    492
  • 访问量
    12032