MST

星途 面试题库

面试题:Ruby 中如何实现区块链简单数据结构

请使用 Ruby 实现一个简单的区块链数据结构,每个区块至少包含索引、时间戳、数据和前一个区块的哈希值。说明实现思路,并写出关键代码。
24.4万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 定义一个 Block 类来表示区块链中的每个区块,包含索引、时间戳、数据和前一个区块哈希值等属性。
  2. 使用 Digest::SHA256 来计算区块的哈希值,哈希值的计算基于当前区块的所有属性。
  3. 定义一个 Blockchain 类来管理整个区块链,包含一个区块数组,并提供添加新区块的方法。

关键代码

require 'digest'

class Block
  attr_accessor :index, :timestamp, :data, :previous_hash

  def initialize(index, timestamp, data, previous_hash)
    @index = index
    @timestamp = timestamp
    @data = data
    @previous_hash = previous_hash
  end

  def hash
    Digest::SHA256.hexdigest(to_s)
  end

  def to_s
    [index, timestamp, data, previous_hash].join
  end
end

class Blockchain
  def initialize
    @chain = [genesis_block]
  end

  def genesis_block
    Block.new(0, Time.now, "Genesis Block", "0")
  end

  def add_block(data)
    previous_block = @chain.last
    new_index = previous_block.index + 1
    new_timestamp = Time.now
    new_block = Block.new(new_index, new_timestamp, data, previous_block.hash)
    @chain << new_block
    new_block
  end

  def chain
    @chain
  end
end

你可以使用以下方式测试代码:

blockchain = Blockchain.new
block1 = blockchain.add_block("Transaction 1")
block2 = blockchain.add_block("Transaction 2")

puts "Blockchain length: #{blockchain.chain.length}"
puts "Block 1 hash: #{block1.hash}"
puts "Block 2 hash: #{block2.hash}"