Skip to content

Instantly share code, notes, and snippets.

@ccastromar
Created February 27, 2020 21:44
Show Gist options
  • Save ccastromar/6b1f87fc7612e296f5f6109aa0cbac57 to your computer and use it in GitHub Desktop.
Save ccastromar/6b1f87fc7612e296f5f6109aa0cbac57 to your computer and use it in GitHub Desktop.
iteracion5 - Serialización
# 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 pickle
import hashlib
import time
import random
import argparse
class Block:
def __init__(self, height, timestamp, data, hash, previous_hash, txs):
self.height = height
self.timestamp = timestamp
self.data = data
self.hash = self.hash_block()
self.previous_hash = previous_hash
self.txs = txs
def serialize_blk(self):
return pickle.dumps(self)
def deserialize_blk(self):
return pickle.loads(self)
def hash_block(self):
sha = hashlib.sha256()
sha.update(self.serialize_blk())
return sha.hexdigest()
@staticmethod
def save_disk(obj):
with open('blks.dat','wb') as hdl:
pickle.dump(obj, hdl)
@staticmethod
def load_disk():
with open('blks.dat','rb') as hdl:
return pickle.load(hdl)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-write', action="store_true", dest="write")
parser.add_argument('-read', action="store_true", dest="read")
args = parser.parse_args()
if (args.write):
bc = list()
for i in range(0,5):
b = Block(i, time.time(), b"data", 0, 0,[])
for j in range(0,3):
n = random.randint(1, 10)
tx = {"nonce":j, "from":"alicia", "to":"roberto", "amount":n, "asset":"ESM"}
b.txs.append(tx)
bc.append(b)
Block.save_disk(bc)
if (args.read):
bc = Block.load_disk()
for b in bc:
print(b.height, b.timestamp, b.data)
print(b.hash, b.previous_hash)
for t in b.txs:
print(t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment