# Timestamping How can you make the blockchain even more secure? Link it to the real world! Let's add a timestamp: ``` ruby Time.now # => 2018-03-17 14:12:01 +0100 ``` or in Epoch time (that is, seconds since January 1st, 1970) ``` ruby Time.now.to_i # => 1521292321 ``` Note: You can use `Time.at` to convert Epoch time back to the standard "classic" format: ``` ruby Time.at( 1521292321 ) # => 2018-03-17 14:12:01 +0100 ``` Now the blockchain must always move forward, that is, you can only add a new block if the timestamp is bigger / younger than the previous block's timestamp. Unbreakable. Unbreakable. Unbreakable. What else? Let's add the proof-of-work difficulty (e.g. '00', '000', '0000' etc.) to the hash to make the difficulty unbreakable / unchangeable too! Last but not least let's drop the "pre-calculated" hash attribute and let's always calculate the hash on demand e.g.: ``` ruby def hash Digest::SHA256.hexdigest( "#{nonce}#{time}#{difficulty}#{prev}#{data}" ) end ``` Remember: Calculating the block's (crypto) hash is fast, fast, fast. What take's time depending on the proof-of-work difficulty is finding the nonce, that is, the lucky number used once. All together now. Resulting in: ``` ruby require 'digest' require 'pp' ## pp = pretty print class Block attr_reader :data attr_reader :prev attr_reader :difficulty attr_reader :time attr_reader :nonce # number used once - lucky (mining) lottery number def hash Digest::SHA256.hexdigest( "#{nonce}#{time}#{difficulty}#{prev}#{data}" ) end def initialize(data, prev, difficulty: '0000' ) @data = data @prev = prev @difficulty = difficulty @nonce, @time = compute_hash_with_proof_of_work( difficulty ) end def compute_hash_with_proof_of_work( difficulty='00' ) nonce = 0 time = Time.now.to_i loop do hash = Digest::SHA256.hexdigest( "#{nonce}#{time}#{difficulty}#{prev}#{data}" ) if hash.start_with?( difficulty ) return [nonce,time] ## bingo! proof of work if hash starts with leading zeros (00) else nonce += 1 ## keep trying (and trying and trying) end end # loop end # method compute_hash_with_proof_of_work end # class Block ``` Proof of the pudding. Let's build a new (more secure) blockchain from scratch (zero). Genesis! ``` ruby b0 = Block.new( 'Hello, Cryptos!', '0000000000000000000000000000000000000000000000000000000000000000' ) #=> #<0x4d00700 cryptos><0x4ed7940 cryptos hello><0x2f297e8 name here><0x4dbd9d0 data>0x4dbd9d0>0x2f297e8>0x4ed7940>0x4d00700>