daily pastebin goal
85%
SHARE
TWEET

Untitled

a guest Jun 1st, 2011 133 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/ruby
  2.  
  3. class BlockHeader
  4.   # Block header          : 160 bytes
  5.   # - Version             : 4 bytes
  6.   # - Previous block hash : 32 bytes
  7.   # - Merkle root         : 32 bytes
  8.   # - Timestamp           : 4 bytes
  9.   # - Bits                : 4 bytes
  10.   # - Nonce               : 4 bytes
  11.  
  12.   attr_accessor :raw,
  13.     :previous_block,
  14.     :nonce,
  15.     :timestamp,
  16.     :version,
  17.     :merkle_root,
  18.     :bits
  19.  
  20.   def initialize(raw)
  21.     self.raw = raw
  22.   end
  23.  
  24.   def raw=(str)
  25.     # We keep only the first 80 bytes of data
  26.     @raw = str[0, 160]
  27.   end
  28.  
  29.   def version
  30.     @version ||= @raw[0, 8].hex
  31.   end
  32.  
  33.   def previous_block
  34.     @previous_block ||= switch_endianness(@raw[8, 64])
  35.   end
  36.  
  37.   def merkle_root
  38.     @merkle_root ||= switch_endianness(@raw[72, 64])
  39.   end
  40.  
  41.   def timestamp
  42.     @timestamp ||= @raw[136, 8].hex
  43.   end
  44.  
  45.   def bits
  46.     @bits ||= @raw[144, 8].hex
  47.   end
  48.  
  49.   def nonce
  50.     @nonce ||= @raw[152, 8].hex
  51.   end
  52.  
  53.   def switch_endianness(str)
  54.     res = []
  55.  
  56.     while str.length > 0 do
  57.       res << str[-8, 8]
  58.       str = str[0, str.length - 8]
  59.     end
  60.    
  61.     res.join
  62.   end
  63.  
  64.   def to_s
  65.     "== Dumping block data\n" +
  66.       " Raw header     : #{raw}\n" +
  67.       " Version        : #{version}\n" +
  68.       " Previous block : #{previous_block}\n" +
  69.       " Merkle root    : #{merkle_root}\n" +
  70.       " Timestamp      : #{timestamp}\n" +
  71.       " Bits           : #{bits}\n" +
  72.       " Nonce          : #{nonce}\n" +
  73.       "=="
  74.   end
  75.  
  76.   def inspect
  77.     puts self
  78.   end
  79. end
  80.  
  81. bh = BlockHeader.new('0000000150c549978a44e3ef671a4ed3f5b922195ebde0fbbccfdb5900e6827000000000c8a03dfb42fa04d47e9fbfd3e6afcb3d0df2b516eb86f4e64d09fe53cc397b6c4de61f4c1c069652a228e13d000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000')
  82.  
  83. bh.inspect
RAW Paste Data
Top