Skip to content

Instantly share code, notes, and snippets.

@ccastromar
Last active February 17, 2020 20:12
Show Gist options
  • Save ccastromar/4490d46f6185ad840128471ab29d88e9 to your computer and use it in GitHub Desktop.
Save ccastromar/4490d46f6185ad840128471ab29d88e9 to your computer and use it in GitHub Desktop.
Blockchain - Iteración 0
# Copyright 2020 Carlos Castro Martos
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import hashlib
import json
import time
class Block:
def __init__(self, height, timestamp, data, prev_hash):
self.height = height
self.timestamp = timestamp
self.data = data
self.prev_hash = prev_hash
self.hash = self.make_hash()
def make_hash(self):
th = hashlib.sha256()
s = str(self.height) + str(self.timestamp) + str(self.data) + str(self.prev_hash)
bs = bytes(s, 'utf-8')
th.update(bs)
return th.digest().hex()
def __repr__(self):
return json.dumps(self.__dict__)
if __name__ == "__main__":
b0 = Block(0, time.time(), 'genesis', 0)
b1 = Block(1, time.time(), 'primero', b0.hash)
b2 = Block(2, time.time(), 'segundo', b1.hash)
blockchain = [b0, b1, b2]
for b in blockchain:
print(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment