示例#1
0
    def __init__(self, is_bootstrap, N, ip="192.168.1.1", port=5000):

        #print("Initializing Node")
        self.id = 0
        self.chain = blockchain.Blockchain()
        self.wallet = wallet.wallet()
        self.ip = ip
        self.port = port
        self.utxo = []
        self.ring = []
        self.current_block = None
        self.current_lock = threading.Lock()
        self.utxo_lock = threading.Lock()
        self.list_lock = threading.Lock()
        self.lengths_lock = threading.Lock()
        self.lengths = []
        self.tx_list = []
        self.conflict = False
        self.num_of_minings = 0
        self.total_mining_time = 0
        self.added_lock = threading.Lock()
        self.N = N

        if is_bootstrap:
            boot_info = {}
            boot_info["address"] = ip + ":" + str(port)
            boot_info["id"] = self.id
            boot_info["key"] = self.wallet.public_key.decode()
            self.ring.append(boot_info)
示例#2
0
def batch():
    #Check variables
    MANDATORY_ENV_VARS = ["hv_mongo_url", "hv_mongo_db", "hv_daemon_url"]
    for var in MANDATORY_ENV_VARS:
        if var not in os.environ:
            raise EnvironmentError("Failed because {} is not set.".format(var))

    bc = blockchain.Blockchain()
    cg = coingecko.Coingecko()
    if 'hv_debug' in os.environ:
        cg.importCurrencies()
        if 'hv_resetrates' in os.environ:
            cg.importExchangePrice(365 * 3)
            cg.importExchangePrice(90)
        cg.importExchangePrice(1)
        bc.scanBlockchain()
    else:
        try:
            with pid.PidFile('havenBatch' + os.environ['hv_mongo_db']) as p:
                print("Starting process on " + os.environ['hv_mongo_db'])
                cg.importCurrencies()
                if 'hv_resetrates' in os.environ:
                    cg.importExchangePrice(365 * 3)
                    cg.importExchangePrice(90)
                cg.importExchangePrice(1)
                bc.scanBlockchain()
        except pid.PidFileError:
            print("Process already running")
        except Exception as e:
            print(e)
示例#3
0
    def test_recv_new_block(self):
        bchain = blockchain.Blockchain()
        old_bchain_len = len(bchain.blockchain)

        #unit testing is really testing an outer layer of the application and hence in order
        #to make process of testing faster and also to ensure that testing does not seep into
        #a great depth but stays only in the outer layer, MOCKING helps, for example if there
        #is an API call in a function(say some HTTPS request), instead of dealing with actual
        #request we can just assume that the server is there to serve the application and
        #start testing the functionality, hence inn unittesting such API calls and onjects should
        #be mocked and tested. I don't want to instansiate the actual blocks to check the blockchian
        #functionality hence I can use MagicMock to mock the blocks and check functionality
        #this actually allows me to not bother making explicitly the blocks with valid/invalid values
        #I can just simulate if blocks are valid in valid by magicmock objects and
        #return value of check functions
        prev_block = MagicMock()
        new_block = MagicMock()
        with self.subTest('newly recieved block is valid and hence should be added'):
            new_block.has_valid_index = MagicMock(return_value=True)
            new_block.has_valid_prev_hash = MagicMock(return_value=True)
            new_block.has_valid_hash = MagicMock(return_value=True)

            bchain.blockchain = [prev_block]
            bchain.recv_new_block(new_block)
            self.assertEqual(len(bchain.blockchain)-old_bchain_len,1)

        with self.subTest('newly received block is invalid and hence should not be added'):
            #any one of them being false is enough to make new_block invalid
            new_block.has_valid_index = MagicMock(return_value=False)
            new_block.has_valid_prev_hash = MagicMock(return_value=False)
            new_block.has_valid_hash = MagicMock(return_value=False)

            bchain.blockchain = [prev_block]
            bchain.recv_new_block(new_block)
            self.assertEqual(len(bchain.blockchain)-old_bchain_len,0)
示例#4
0
    def __init__(self, bootstrap, number, port, ipbootstrap, ip_dikia_mou):
        self.port = port
        self.chain = blockchain.Blockchain()
        self.current_id_count = 0  #register_node_to_ring()
        self.wallet = wallet.wallet()
        #self.NBCs = self.wallet.balance()
        temp = "http://" + ipbootstrap + ":5000"
        self.ring = [
            temp
        ]  #here we store information for every node, as its id, its address (ip:port) its public key and its balance
        self.nei = number
        self.public_key_list = []
        self.myip = ip_dikia_mou

        if (bootstrap == "0"):
            self.public_key_list = [self.wallet.public_key]
            self.id = 0
            self.chain.create_genesis(number, self.public_key_list[0])
            #print("my chain list " , self.chain.list[0].output())
            self.wallet.add_genesis(self.chain.list[0].output())
            self.e = threading.Event()
            self.e.clear()
            t2 = threading.Thread(target=self.init)
            t2.start()
        else:
            self.my_reg()
示例#5
0
    def __init__(self):
        # Networking stuff
        self.HEADER = 4069  # Expected file receive size, 4 kilobytes
        self.PORT = 5050  # The port in which we will be 'listening and talking' through
        self.IP = socket.gethostbyname(
            socket.gethostname())  # find my local ip
        self.ADDR_SERVER = (self.IP, self.PORT)

        self.server = socket.socket(
            socket.AF_INET,
            socket.SOCK_STREAM)  # Create a socket obj for allowing connections
        self.server.bind(
            self.ADDR_SERVER)  # 'Bind' it on this machine on port 5050
        self.clients = []  # Store all current and imcoming connections
        self.run = True  # If the network should be active

        # Blockchain Stuff
        self.ledger = blockchain.Blockchain()
        self.ledger.printChainInfo()
        '''
        For one client the code below works, but to handle multiple clients
        we only connect to a node when we need to and disconnect right after
        '''
        # self.ADDR_CLIENT = ("10.0.0.113", self.PORT)
        # self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # self.client.connect(self.ADDR_CLIENT)
        # self.servers = []
        '''
示例#6
0
	def updateChain(self, ret = True):
		chainChoice =  {}
		self.updateNeighbours(ret = False)
		self._neighboursMutex.acquire()
		for k, v in self.getNeighbours().items():
			if v.ping:
				id = v.id()
				chain_hash = self.getChainHashOfId(id)
				if chain_hash:
					if chain_hash not in chainChoice:
						chainChoice[chain_hash] = [id, 0]
					else:
						chainChoice[chain_hash][1] += 1
		node.mutexReleaser(self._neighboursMutex)
		max_vote = 1
		my_id = self.id()
		max_voted_chain_id = my_id
		for k, v in chainChoice.items():
			if v[1] > max_vote:
				max_vote = v[1]
				max_voted_chain_id = v[0]
		if max_voted_chain_id != my_id:
			chain = self.getChainOfId(max_voted_chain_id)
			if chain:
				self._chainMutex.acquire()
				pendTransactions = self._chain.pendingTransactions
				self._chain = blockchain.Blockchain(chain)
				for k, v in pendTransactions.items():
					self._chain.addTransaction(k, v)
				node.mutexReleaser(self._chainMutex)
		return ret
示例#7
0
def premine():
    global PITCOIN
    print(color.OKGREEN +
          "Premine mode is active now.\nGenerating 3 private keys...")
    keys_adds = {}
    keys = []
    addresses = []
    for i in range(3):
        keys.append(str(wallet.GenerateNewPrivateKey()))
        open("key" + str(i),
             'w').write(str(wallet.privateKeyToWif(keys[i]))[2:-1])
        addresses.append(str(wallet.GetNewPublicAdress(keys[i]))[2:-1])
        keys_adds[keys[i]] = addresses[i]
    open("minerkey", 'w').write(str(wallet.privateKeyToWif(keys[0]))[2:-1])
    open("address", 'w').write(addresses[0])
    print(
        "Keys was saved in files key[0-2].\nAlso minerkey from the first key and miner address files were created."
        + color.BOLD)
    PITCOIN = blockchain.Blockchain()
    PITCOIN.genesis_block()
    addRandomTxsToPool(keys_adds, 30)
    for x in range(10):
        new_block = block.InitNewBlock(PITCOIN.chain[-1].hash)
        print("New block has been mined and added to a chain.\nBlock hash =",
              new_block.hash)
        PITCOIN.AddNewBlock(new_block)
    saveBlockchainToFile(PITCOIN)
    print(color.ENDC)
示例#8
0
	def test_save(self):
		bc4 = blockchain.Blockchain()
		firstBlockData = b'This is the first block. Should have index 1'
		secondBlockData = b'This is the second block. Should have index 2'
		bc4.addBlock(firstBlockData)
		bc4.addBlock(secondBlockData)
		bc4.save('testSave.bc')
		self.assertTrue(os.path.isfile('./testSave.bc'))
示例#9
0
    def __init__(self, port):
        self.peers = []
        self.chain = blockchain.Blockchain()
        self.chain.genesis()
        self.staging = []  # staging data to add to block

        # socket stuff
        self.port = port
示例#10
0
 def __init__(self, port = 8080):
 
     self.testargs = " ".join(sys.argv[1:])
     self.publickey, self.privatekey = rsa.newkeys(512)
     self.host = ''   # <-- works on all available network interfaces
     self.port = port
     self.chain = blockchain.Blockchain()
     self.phonebook = Phonebook()
     self.uid = uuid.uuid1()
示例#11
0
    def __init__(self, port=NODE_PORT):
        self.gblockchain = None
        try:
            self.gblockchain = blockchain.Blockchain(URL, port)

        except Exception as msg:
            print(str(msg))
            sys.exit()
        super(MinerCli, self).__init__()
示例#12
0
def test_add_transaction():
    my_blockchain = blockchain.Blockchain(
    )  # first, initiate a blockchain object
    # add it to the mempool
    my_blockchain.add_new_transaction(my_transaction)
    # loop through all the transactions and check to see if that transaction is in the pool
    for transaction in my_blockchain.unconfirmed_transactions:
        # check whether our transaction is in the list of uncofirmed transaction
        assert transaction == my_transaction
示例#13
0
 def __init__(self, address, port):
     self.connectedUsernames = ["Smart Grid"]
     self.connectedIDs = [str(uuid4())]
     self.connectedAddresses = ["127.0.0.1"]
     self.connectedPorts = ["6789"]
     self.numPeers = 0
     self.tracker = self.startTracker(address, port)
     self.bc = blockchain.Blockchain()
     self.cont = True
示例#14
0
    def __init__(self, node_identifier):
        """
		Initialize a blockchain object
		BUFFER_MAX_LEN is the number of entries per block
		"""
        self.blockchain = bc.Blockchain(node_identifier)
        self.BUFFER_MAX_LEN = 20
        self.MINE_REWARD = 10
        self.node_identifier = node_identifier
示例#15
0
文件: db.py 项目: cornliu/Blockchain
 def __init__(self, db_file):
     self._db_file = db_file
     try:
         with open(self._db_file, 'rb') as f:
             self.kv = pickle.load(f)
     except:
         with open(self._db_file, 'wb') as f:
             newblockchain = blockchain.Blockchain()
             pickle.dump(newblockchain, f)
             self.kv = newblockchain
示例#16
0
    def test_generate_new_block(self):
        bchain = blockchain.Blockchain() #this is really a class object which actually contains the blockchain
        old_bchain_len = len(bchain.blockchain)

        data = "this is a new block's data"

        with self.subTest('add new block to blockchain'):
            bchain.generate_next_block(data)
            self.assertEqual(len(bchain.blockchain)-old_bchain_len,1)
            self.assertEqual(bchain.get_latest_block().data, data)
示例#17
0
 def do_add_node(self, arg):
     """adds a node to a blockchain"""
     if (PITCOIN is None):
         inp = input(
             "There is no chain in memory\nType 'new' if you want to create a new chain otherwise type a file name to import from\n(new/'filename')\n"
         )
         if inp == "new":
             PITCOIN = blockchain.Blockchain()
             PITCOIN.genesis_block()
             PITCOIN.add_node(arg)
     saveBlockchainToFile(PITCOIN)
示例#18
0
 def __init__(self, address):
     ##set
     self.chain = blockchain.Blockchain()
     self.current_id_count = 1
     self.address = address
     self.wallet = wallet.wallet(address)
     # here we store information for every node, as its id, its address (ip:port) its public key and its balance
     self.peers = ({str(self.wallet.publickey.decode('utf-8')): address})
     self.id_ip = {"id0": address}
     self.wallets = {}
     self.lock = threading.Lock()
     self.commitLock = threading.Lock()
示例#19
0
	def __init__(self, address, chain, current_block=None, node_id=0, NBC=0, ring=[]):
		##set

		self.chain = blockchain.Blockchain()
		self.id = node_id
		self.NBC = NBC		
		self.address = address # Address is a string
		self.wallet = self.create_wallet()
		self.ring = ring  #here we store information for every node, as its id, its address (ip:port) its public key and its balance 
		self.current_block = current_block
		self.block_ids = 1
		self.difficulty = 5
示例#20
0
	def test_save_extraMetadata(self):
		bc4 = blockchain.Blockchain()
		firstBlockData = b'This is the first block. Should have index 1'
		secondBlockData = b'This is the second block. Should have index 2'
		bc4.addBlock(firstBlockData)
		bc4.addBlock(secondBlockData)
		bc4.save('testSave2.bc', {'finances':{
				'Alice':0.001,
				'Bob':0.072
			}
		})
		self.assertTrue(os.path.isfile('./testSave2.bc'))
示例#21
0
def sample_blockchain_setup():
    blockchain_app = blockchain.Blockchain()
    blockchain_app.new_transaction("Rajiv", "Tanush", '5 BTC')
    blockchain_app.new_transaction("Tanush", "Pradyumna", '1 BTC')
    blockchain_app.new_transaction("Pradyumna", "Rajiv", '7 BTC')
    blockchain_app.new_block()

    blockchain_app.new_transaction("Elon Musk", "Bill Gates", '100 BTC')
    blockchain_app.new_transaction("Bill Gates", "Jeff Bezos", '250 BTC')
    blockchain_app.new_transaction("Jeff Bezos", "Mark Zuckerberg", '720 BTC')
    blockchain_app.new_block()

    return blockchain_app.return_blockchain()
示例#22
0
文件: user.py 项目: sosooding/ARTCoin
	def __init__(self, name, password):

		self.name = name
		self.password = password
		self.private_key = None
		self.public_key = None
		self.balance = 0
		self.pending_updates = Queue.Queue()
		self.ledger = blockchain.Blockchain()
		self.id = None
		self.root = None

		self.createKeys()
示例#23
0
	def test_getBlockData_ValidIndex(self):
		bc2 = blockchain.Blockchain()
		firstBlockData = b'This is the first block. Should have index 1'
		secondBlockData = b'This is the second block. Should have index 2'
		bc2.addBlock(firstBlockData)
		bc2.addBlock(secondBlockData)
		
		genesisBlock = bc2.getBlockData(0)
		firstBlock = bc2.getBlockData(1)
		secondBlock = bc2.getBlockData(2)
		self.assertNotEqual(genesisBlock, False)
		self.assertEqual(firstBlock, firstBlockData)
		self.assertEqual(secondBlock, secondBlockData)
示例#24
0
def work_flow():
    chain = blockchain.Blockchain()
    while (True):
        print("Menu")
        print("---> process new transaction")
        print("---> view blockchain")

        choice = int(input())

        if (choice == 1):
            chain.add_block(process_request())
        else:
            chain.print_chain()
示例#25
0
def dbCheck():
    db = sqlite3.connect(databaseLocation)
    cursor = db.cursor()
    cursor.execute('SELECT * FROM blocks WHERE id = (SELECT MAX(id) FROM blocks)')
    # Last block from own database
    lastBlock_db = cursor.fetchone()
    bc = blockchain.Blockchain(lastBlock_db)
    # Empty database
    if not lastBlock_db:
        genesis = bc.getLastBlock()
        writeBlock(genesis)
    db.commit()
    db.close()
    return bc
示例#26
0
 def __init__(self, is_premine=0):
     cmd.Cmd.__init__(self)
     self.prompt = "฿ "
     self.intro = "\t\tWelcome to the miner cli\nHow to use? 'help'!!"
     self.doc_header = "For detail information use 'help _command_')"
     self.blockchain = pp.get_data("blockchain.pickle")
     if (self.blockchain == False or is_premine == True):
         os.remove("utxo.pickle")
         self.blockchain = blockchain.Blockchain()
         if is_premine == True:
             print("PREMINE IS ON")
             pubkeys = premine.createKeysAndAddresses()
         self.blockchain.genesis_block()
         if is_premine == True:
             premine.premine_mode(pubkeys, self)
示例#27
0
class TestBlockChainMethods(unittest.TestCase):
    chain = blockchain.Blockchain()

    def test_newBlock(self):
        block = self.chain.new_block(100, 123)
        self.assertEqual(block["proof"], 100)
        self.assertEqual(block["previous_hash"], 123)

    def test_validate_prof(self):
        self.assertTrue(self.chain.valid_proof(1, 72608))
        self.assertFalse(self.chain.valid_proof(1, 2))

    def test_proof_of_work(self):
        self.assertEqual(self.chain.proof_of_work(1), 72608)
        self.assertEqual(self.chain.proof_of_work(2), 69926)
        self.assertNotEqual(self.chain.proof_of_work(2), 3)
示例#28
0
文件: actor.py 项目: ML4Ops/OpsRE
def test():

    LEVELS = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    # if len(sys.argv) > 1:
    # level_name = sys.argv[1]
    level_name = 'operations'
    level = LEVELS.get(level_name, logging.NOTSET)
    logging.basicConfig(level=level)
    print 'Start operations log file'
    print(logging.getLoggerClass().root.handlers[0].baseFilename)

    LOG_FILENAME = 'example.log'
    logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
    logging.debug('This message should go to the log file')

    logging.debug('This is a debug message')
    logging.info('This is an info message')
    logging.warning('This is a warning message')
    logging.error('This is an error message')
    logging.critical('This is a critical error message')

    chain = blockchain.Blockchain()
    logging.info('Blockchain initialized')

    white = Actor('White')
    logging.info('White Actor Created')

    red = Actor('Red')
    logging.info('Red Actor Created')

    blue = []
    blue_strategic = Actor('Blue/Strategic')
    blue.append(blue_strategic)
    blue_operational = Actor('Blue/Operational')
    blue.append(blue_operational)
    blue_tactical = Actor('Blue/Tactical')
    blue.append(blue_tactical)
    logging.info('Blue Strategic, Operational and Tactical Actors Created')

    return 1
示例#29
0
def create_chain_from_dump(chain_dump):
    newblockchain = blockchainModule.Blockchain()
    for idx, block_data in enumerate(chain_dump):
        newblock = block.Block(block_data["index"],
                               block_data["previous_hash"],
                               block_data["transactions"])
        newblock.timestamp = block_data["timestamp"]
        proof = block_data['hash']
        if idx > 0:
            newblock.nonce = block_data["nonce"]
            added = newblockchain.add_block(newblock, proof)
            if not added:
                raise Exception("The chain dump is tampered!!")
        else:  # else the block is a genesis block, no verification needed
            newblock.hash = proof
            newblockchain.chain.append(newblock)
    return newblockchain
示例#30
0
 def __init__(self, node):
     self.node = node
     self.rating = rating.RatingBase()
     self.work_time = time.time()
     self.blockchain = blockchain.Blockchain()
     self.amount_of_valid = 0
     self.percent = 0
     self.voted = set()
     self.virus_people = 0
     self.validators = dict()
     self.threads = []
     self.time_for_vote = None
     self.time_of_voting_end = None
     self.graph = nx.Graph()
     self.figure = plt.figure()
     self.show_plot()
     self.start_listen()